下面将为您详细分步骤讲解在SpringBoot中引入MyBatisPlus的常规操作:
第一步:在pom.xml中引入MyBatisPlus的依赖
在SpringBoot项目的pom.xml中添加以下依赖:
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.2</version>
</dependency>
第二步:配置MyBatisPlus
在SpringBoot项目的application.properties或application.yml中添加以下配置:
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
username: root
password: mypassword
mybatis-plus:
configuration:
map-underscore-to-camel-case: true # 开启驼峰命名规则(例如:user_name -> userName)
第三步:编写Mapper接口
MyBatisPlus通过继承BaseMapper类实现通用的CRUD操作,因此只需编写Mapper接口即可。
例如,编写一个UserMapper接口,继承BaseMapper类:
public interface UserMapper extends BaseMapper<User>
第四步:编写实体类与Mapper.xml文件
以User实体类为例,编写user实体类和用户Mapper.xml文件。User实体类可以使用Lombok快速生成Getter、Setter等方法:
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String username;
private Integer age;
private String email;
}
配置userMapper.xml文件:
<?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="username" property="username"/>
<result column="age" property="age"/>
<result column="email" property="email"/>
</resultMap>
<sql id="Base_Column_List">
id, username, age, email
</sql>
<select id="selectAll" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from user
</select>
<insert id="insertUser" parameterType="com.example.demo.entity.User">
insert into user (username, age, email)
values (#{username}, #{age}, #{email})
</insert>
</mapper>
第五步:实现Service层
编写UserService.java接口和UserServiceImpl.java实现类:
public interface UserService {
List<User> selectAll();
boolean insertUser(User user);
}
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public List<User> selectAll() {
return userMapper.selectList(null);
}
@Override
public boolean insertUser(User user) {
return userMapper.insert(user) == 1;
}
}
第六步:测试
编写UserController类进行测试:
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/users")
public List<User> selectAll() {
return userService.selectAll();
}
@PostMapping("/user")
public boolean insertUser(@RequestBody User user) {
return userService.insertUser(user);
}
}
其中,/users接口可以查询全部用户列表,/user接口可以添加一个用户。
通过以上步骤,我们就成功在SpringBoot中引入MyBatisPlus,并实现了常规的CRUD操作。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:SpringBoot中引入MyBatisPlus的常规操作 - Python技术站