根据ID查询用户
//根据ID查询用户
@Test
public void testSelectById(){
User user = userMapper.selectById(1L);
System.out.println(user);
}
批量查询
@Test
public void testSelectByBatchId(){
List<User> users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3));
users.forEach(System.out::println);
}
条件查询
@Test
public void testSelectByBatchIds(){
HashMap<String, Object> map = new HashMap<>();
//自定义条件查询,查询name=zhangsan并且age=19的用户
map.put("name","zhangsan");
map.put("age",19);
List<User> users = userMapper.selectByMap(map);
users.forEach(System.out::println);
}
分页在网站使用十分之多!
编写mybatis-plus配置类
// 最新版
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2));
return interceptor;
}
编写测试类
//测试分页查询
@Test
public void testPage(){
//参数一:第一页 参数二:页面显示5条数据
Page<User> page = new Page<>(1,5);
userMapper.selectPage(page,null);
page.getRecords().forEach(System.out::println);
}
测试结果
通过ID删除
@Test
public void testDeleteById(){
userMapper.deleteById("1410758327595810819L");
}
控制台输出
查看数据库
批量删除
@Test
public void testDeleteBatchId(){
userMapper.deleteBatchIds(Arrays.asList(1410758327595810818L,7L,6L));
}
控制台输出
查看数据库
条件删除
@Test
public void testDeleteMap(){
HashMap<String, Object> map = new HashMap<>();
map.put("name","zhangsan2");
userMapper.selectByMap(map);
}
控制台输出
查看数据库
物理删除:从数据库中直接移除
逻辑删除:在数据库中没有被移除,而是通过一个变量来让他失效!deleted = 0 or deleted = 1
管理员可以查看被删除的记录!防止数据丢失,类似于回收站
1、在数据库中添加一个deleted字段
2、在实体类中添加属性
@TableLogic //逻辑删除注解
private Integer deleted;
3、配置
特别注意:mybatis-plus 3.3版本之后,不需要配置application配置文件,直接使用注解即可!不然会报错
mybatis-plus 3.3版本以上自行忽略一下配置
mybatis-plus:
global-config:
db-config:
logic-delete-field: flag # 全局逻辑删除的实体字段名(since 3.3.0,配置后属性可以不用添加注解)
logic-delete-value: 1 # 逻辑已删除值(默认为 1)
logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)
测试
控制台输出
查看数据库
Springboot(十三)——整合mybatis-plus(三)
原文:https://www.cnblogs.com/luoxiao1104/p/14962703.html