下面我将介绍Spring Boot整合Mybatis-Plus的详细方法,包括项目环境搭建、依赖引入、配置文件设置、代码实现等内容。
环境搭建
在进行整合前首先需要搭建好Spring Boot项目的开发环境,可以使用IDE工具,如IntelliJ IDEA、Eclipse等,也可以通过Spring Initializr快速生成一个Spring Boot项目的基础结构。
依赖引入
在pom.xml中添加Mybatis-Plus和MySQL的依赖:
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
配置文件设置
在application.yml或application.properties中添加数据库的配置信息:
spring:
datasource:
url: jdbc:mysql://localhost:3306/springboot_mybatisplus_demo?UseUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: root
jpa:
show-sql: true
mybatis-plus:
mapper-locations: classpath*:mapper/*.xml
configuration:
map-underscore-to-camel-case: true
其中,datasource配置了数据库的连接信息,mybatis-plus的mapper-locations配置了mapper文件存放路径,并将数据库中的下划线命名自动转换为Java的驼峰式命名。
代码实现
整合Mybatis-Plus的核心代码就是创建一个mapper接口并继承Mybatis-Plus的BaseMapper接口,自动继承了常用的增、删、改、查等方法:
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
另外,可以在mapper接口中自定义SQL语句或使用注解实现更为复杂的操作。
至此,Spring Boot整合Mybatis-Plus的方法就介绍完毕了。
下面分别给出Spring Boot整合Mybatis-Plus的XML配置和注解配置两个示例。
XML配置
- 配置pom.xml文件
添加需要用到的依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.3.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
<version>2.3.4.RELEASE</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
- 配置application.yml文件
添加数据库相关的配置:
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/db_test?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
username: root
password: root
jpa:
show-sql: true
mybatis-plus:
mapper-locations: classpath*:mapper/*.xml
- 创建mapper接口继承BaseMapper
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
- 创建User类
@Data
@TableName("t_user")
public class User {
private Long id;
private String name;
private Integer age;
}
- 创建SQL文件
在src/main/resources/mapper下创建UserMapper.xml,编写相应的SQL语句。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.mapper.UserMapper">
<resultMap id="BaseResultMap" type="com.example.demo.entity.User">
<id column="id" property="id" />
<result column="name" property="name" />
<result column="age" property="age" />
</resultMap>
<sql id="Base_Column_List">
id, name, age
</sql>
<select id="selectById" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List"/>
FROM t_user
WHERE id = #{id}
</select>
<select id="selectAll" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List"/>
FROM t_user
</select>
<insert id="insert" parameterType="com.example.demo.entity.User" useGeneratedKeys="true" keyProperty="id" >
INSERT INTO t_user(name,age) VALUES(#{name},#{age})
</insert>
<update id="update" parameterType="com.example.demo.entity.User">
UPDATE t_user SET name=#{name} WHERE id=#{id}
</update>
<delete id="deleteById" parameterType="Long">
DELETE FROM t_user WHERE id=#{id}
</delete>
</mapper>
- 创建Service和Controller层
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User findById(Long id) {
return userMapper.selectById(id);
}
@Override
public List<User> findAll() {
return userMapper.selectList(null);
}
@Override
public int save(User user) {
return userMapper.insert(user);
}
@Override
public int update(User user) {
return userMapper.updateById(user);
}
@Override
public int deleteById(Long id) {
return userMapper.deleteById(id);
}
}
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/{id}")
public User findById(@PathVariable Long id) {
return userService.findById(id);
}
@GetMapping("/")
public List<User> findAll() {
return userService.findAll();
}
@PostMapping("/")
public int save(User user) {
return userService.save(user);
}
@PutMapping("/")
public int update(User user) {
return userService.update(user);
}
@DeleteMapping("/{id}")
public int deleteById(@PathVariable Long id) {
return userService.deleteById(id);
}
}
至此,整合Mybatis-Plus的示例代码就完成了。在这个示例中,我们使用了XML形式的mapper文件来完成SQL语句的编写和数据的增、删、改、查操作。XML的方式相对于注解的方式可以更为灵活地进行各种复杂的SQL操作。
注解方式配置
- 修改pom.xml文件
添加mybatis-plus和mysql的依赖:
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
- 添加配置
在application.yml或application.properties中配置数据源和mybatis-plus的相关信息:
server:
port: 8080
spring:
datasource:
url: jdbc:mysql://localhost:3306/mybatisplus?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
show-sql: true
# mybatis-plus
mybatis-plus:
# 扫描mapper.xml文件
mapper-locations:
- classpath:/mapper/*.xml
# mybatis-plus配置
configuration:
map-underscore-to-camel-case: true
- 创建User和UserMapper
User类:
@Data
public class User {
private Long id;
private String name;
private Integer age;
}
UserMapper类:
@Mapper
public interface UserMapper extends BaseMapper<User> {
// 基本的CRUD操作,都不用自己写了
/**
* 根据名称查找
*
* @param name 名称
* @return User
*/
@Select("SELECT * FROM user WHERE name=#{name}")
User findByName(@Param("name") String name);
}
在Mybatis-Plus中继承了BaseMapper之后,就已经具备了基本的CRUD操作,无需自己再写SQL语句了。这里演示了一个自定义的查询操作。
- 编写controller与service
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User getById(Long id){
return userMapper.selectById(id);
}
@Override
public boolean save(User user) {
return userMapper.insert(user) > 0;
}
@Override
public boolean updateById(User user) {
return userMapper.updateById(user) > 0;
}
@Override
public boolean removeById(Long id) {
return userMapper.deleteById(id) > 0;
}
}
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/{id}")
public User getOne(@PathVariable Long id){
return userService.getById(id);
}
@PostMapping("/")
public String create(User user){
return userService.save(user) ? "success" : "failed";
}
@PutMapping("/")
public String update(User user){
return userService.updateById(user) ? "success" : "failed";
}
@DeleteMapping("/{id}")
public String delete(@PathVariable Long id){
return userService.removeById(id) ? "success" : "failed";
}
@GetMapping("/find")
public User findByName(String name){
return userService.findByName(name);
}
}
至此,整合Mybatis-Plus的注解方式配置就完成了。在这个示例中,我们使用了基本的CRUD操作和自定义的查询操作。注解方式相对于XML的方式也很灵活,不需创建XML文件,所有SQL语句都使用注解的形式在代码中体现。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:springboot整合mybatisplus的方法详解 - Python技术站