快捷搜索: 王者荣耀 脱发

使用tkMapper进行增删改查

0. tkMapper引入

  1. tkMapper就是一个MyBatis插件,是在MyBatis的基础上提供了很多工具,让开发变得简单,提高开发效率。
  2. 引入依赖: <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper-spring-boot-starter</artifactId> <version>${tk.mybatis.version}</version> </dependency>
  3. 创建一个与数据库表相匹配的实体类,如: @Data @Builder @NoArgsConstructor @AllArgsConstructor public class StudentInfo { @Id private Long id; /** * 姓名 */ private String name; /** * 手机号 */ private String mobile; /** * 学号 */ private String studentId; /** * 班级编号 */ private String classId; /** * 创建时间 */ private Date ctime; /** * 更新时间 */ private Date mtime; /** * 删除标志 0:未删除 1:删除 */ private Integer deleted_status; }
  4. 创建mapper接口: public interface StudentInfoMapper<StudentInfo> extends Mapper<StudentInfo>, MySqlMapper<StudentInfo>, BatchMapper<StudentInfo>, GroupMapper<StudentInfo> { }
  5. 接下来为大家简要介绍一下几种常用的tkMapper的增删改查方法,还有很多没有介绍到,大家可以移步tkMapper官方文档获取更加详细的信息~

1. 插入数据

1.1. insert

使用insert,如果数据的某项值为null,则会直接向数据库表中的对应列插入null,不推荐使用。

StudentInfo info = StudentInfo.builder()
  .name("Zhangsan")
  .mobile("12312341234")
  .build();

studentInfoMapper.insert(info);

比如上面这种写法,插入数据库中的该条记录的其他字段将会是null;

1.2. insertSelective

使用insertSelective,如果数据的某项值为null,则会直接向数据库表中的对应列插入数据库表设定的默认值,推荐使用。

StudentInfo info = StudentInfo.builder()
  .name("Zhangsan")
  .mobile("12312341234")
  .build();

studentInfoMapper.insertSelective(info);

比如上面这种写法,插入数据库中的该条记录的其他字段将会是数据库表的默认值;

1.3. insertList

使用insertList,可以一次性向数据库表中插入多条记录。

List<StudentInfo> infoList = XXXX;

studentInfoMapper.insertList(infoList);

2. 查询数据

2.1. selectAll

使用selectAll,直接查询出所有数据。

List<StudentInfo> infoList = studentInfoMapper.selectAll();

2.2 selectByPrimaryKey

使用selectByPrimaryKey,根据主键进行查询。

StudentInfo info = studentInfoMapper.selectByPrimaryKey(15);

2.3. 使用selectByExample / selectOneByExample进行条件查询

详见另一篇文章:

2.4. 分页查询

详见另一篇文章:

3. 更新数据

3.1. updateByExampleSelective

如果我们想根据学生的学号对学生信息进行更新,那么我们可以使用如下方式:

Weekend<StudentInfo> weekend = Weekend.of(StudentInfo.class);
WeekendCriteria<StudentInfo, Object> weekendCriteria = weekend.weekendCriteria();
weekendCriteria.andEqualTo(StudentInfo::getStudentId, studentId);
weekendCriteria.andEqualTo(StudentInfo::getDeletedStatus, 0);
StudentInfo info = studentInfoMapper.selectOneByExample(weekend);
if (Objects.isNull(info)) {
          
   
    throw new 这里可以自定义异常抛出;
}
StudentInfo infoNeedToUpdate = 需要更新的数据;
studentInfoMapper.updateByExampleSelective(infoNeedToUpdate, weekend);

先进行查询,确保要更新的数据是存在的,再进行更新;

4. 删除数据

一般在业务中,禁止使用物理删除,所有我们常用的逻辑删除往往只是更新deletedStatus状态为“已删除”即可,此处应使用更新数据的方法,不再赘述;

经验分享 程序员 微信小程序 职场和发展