- 0. tkMapper引入
- 1. 插入数据
- 1.1. insert
- 1.2. insertSelective
- 1.3. insertList
- 2. 查询数据
- 2.1. selectAll
- 2.2 selectByPrimaryKey
- 2.3. 使用selectByExample / selectOneByExample进行条件查询
- 2.4. 分页查询
- 3. 更新数据
- 3.1. updateByExampleSelective
- 4. 删除数据
- tkMapper就是一个MyBatis插件,是在MyBatis的基础上提供了很多工具,让开发变得简单,提高开发效率。
- 引入依赖:
tk.mybatis mapper-spring-boot-starter ${tk.mybatis.version} - 创建一个与数据库表相匹配的实体类,如:
@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; private Integer deleted_status; } - 创建mapper接口:
public interface StudentInfoMapper
extends Mapper , MySqlMapper , BatchMapper , GroupMapper { } - 接下来为大家简要介绍一下几种常用的tkMapper的增删改查方法,还有很多没有介绍到,大家可以移步tkMapper官方文档获取更加详细的信息~
使用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,可以一次性向数据库表中插入多条记录。
List2. 查询数据 2.1. selectAllinfoList = XXXX; studentInfoMapper.insertList(infoList);
使用selectAll,直接查询出所有数据。
List2.2 selectByPrimaryKeyinfoList = studentInfoMapper.selectAll();
使用selectByPrimaryKey,根据主键进行查询。
StudentInfo info = studentInfoMapper.selectByPrimaryKey(15);2.3. 使用selectByExample / selectOneByExample进行条件查询
详见另一篇文章:tkMapper之使用Weekend拼接条件进行条件查询
2.4. 分页查询详见另一篇文章:MyBatis之使用PageHelper插件进行分页查询
3. 更新数据 3.1. updateByExampleSelective如果我们想根据学生的学号对学生信息进行更新,那么我们可以使用如下方式:
Weekendweekend = Weekend.of(StudentInfo.class); WeekendCriteria 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状态为“已删除”即可,此处应使用更新数据的方法,不再赘述;



