mybatisplus CRUD常用方法
查询
单个主键查询
//通过单个主键查询
Student student = studentMapper.selectById("1414125536583036929");
System.out.println(student);
多个主键查询
//通过多个主键查询
List<Student> students = studentMapper.selectBatchIds(Arrays.asList(
"1414125536583036929", "1414132766216757250", "1414133065828499457"));
students.forEach(System.out::println);
map条件查询
HashMap<String, Object> map = new HashMap<>();
map.put("stuName","溪风");
map.put("stuAge",20);
//条件查询
List<Student> students = studentMapper.selectByMap(map);
students.forEach(System.out::println);
//生成的语句如下
//SELECT stuId,stuName,stuSex,stuAddress,stuAge,version,create_time AS createTime,update_time AS updateTime FROM student WHERE stuName = ? AND stuAge = ?
分页查询
添加分页拦截
@Configuration
@MapperScan("com.lwp.study.dao")
@EnableTransactionManagement //开启事务
public class MybatisPlusConfig {
/**
* 拦截器处理乐观锁和分页
* @return
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
//添加分页拦截
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
代码实操
//参数1:第几页(1开始,传入0和1一样),参数2:每页显示数量
IPage<Student> page=new Page(2,2);
studentMapper.selectPage(page,null);
//获取分页后的记录数
page.getRecords().forEach(System.out::println);
//获取当前的页数
System.out.println(page.getCurrent());
//当前分页的总页数
System.out.println(page.getPages());
//获取当前每页显示多少条
System.out.println(page.getSize());
//当前满足条件总行数,既select count(*) from xx where xxx=xxx的值
System.out.println(page.getTotal());
删除
物理删除
//通过单个主键删除
int i = studentMapper.deleteById("1414204070248828930");
//通过多个主键删除
int i1 = studentMapper.deleteBatchIds(Arrays.asList(
"1b0a2643082c63db81a182f144967d9f",
"87107e33b1c2ac3486d19c4d3a18ce08"
));
//通过条件删除
HashMap<String, Object> map = new HashMap<>();
map.put("stuName","呵呵");
int i2 = studentMapper.deleteByMap(map);
逻辑删除
添加逻辑删除标识字段
@TableLogic //标识逻辑删除注解,字段名和yaml配置的全局一致,可不需要该注解
private Integer deleted;
配置yaml
mybatis-plus:
global-config:
db-config:
logic-delete-field: deleted # 全局逻辑删除的实体字段名(since 3.3.0,配置后可以忽略不配置步骤2)
logic-delete-value: 1 # 逻辑已删除值(默认为 1)
logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)
测试
//通过单个主键删除
int i = studentMapper.deleteById("1414133065828499457");
//实际执行的语句
//UPDATE student SET deleted=1 WHERE stuId=? AND deleted=0
注意点
插入: 不作限制
查找: 追加where条件过滤掉已删除数据,且使用 wrapper.entity 生成的where条件会忽略该字段
更新: 追加where条件防止更新到已删除数据,且使用 wrapper.entity 生成的where条件会忽略该字段
删除: 转变为 更新
例如:
删除: update user set deleted=1 where id = 1 and deleted=0
查找: select id,name,deleted from user where deleted=0
新增
//会根据传入的参数拼接动态sql进行新增
Student stu=new Student();
stu.setStuName("呵呵");
stu.setStuAge(18);
//返回受影响的行数
int resultValue = studentMapper.insert(stu);
修改
//会根据传入的参数拼接动态sql进行修改
Student student = studentMapper.selectById("1414125536583036929");
student.setStuName("魔尊");
studentMapper.updateById(student1);