首页 > 编程语言 > 详细

Springboot(十三)——整合mybatis-plus(三)

时间:2021-07-02 15:16:24      阅读:10      评论:0      收藏:0      [点我收藏+]

Springboot(十三)——整合mybatis-plus(三)

查询操作

根据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);
}

技术分享图片

分页查询操作

分页在网站使用十分之多!

  • 1、原始的limit进行分页
  • 2、pageHelper第三方插件
  • 3、Mybatis-plus内置插件

编写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);
}

控制台输出
技术分享图片
查看数据库
技术分享图片

逻辑删除

官方文档:https://mp.baomidou.com/guide/logic-delete.html

物理删除:从数据库中直接移除
逻辑删除:在数据库中没有被移除,而是通过一个变量来让他失效!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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!