首页 > 其他 > 详细

第121天学习打卡(MyBatisPlus CRUD扩展之查询操作 分页查询 删除操作 逻辑删除 条件构造器 自动生成器 )

时间:2021-05-10 00:20:29      阅读:27      评论:0      收藏:0      [点我收藏+]

CRUD扩展

查询操作

在test里面进行测试:

   //查询测试
     @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);
    }
     //按条件查询之一 使用 map
     @Test
     public void testSelectByBatchIds(){
         HashMap<String, Object> map = new HashMap<>();
         //自定义查询
         map.put("name","狂神说Java");
         map.put("age",3);
         List<User> users = userMapper.selectByMap(map);
         users.forEach(System.out::println);
 ?
    }
 ?

分页查询

分页在网站的使用很多

1.原始的limit进行分页

2.pageHelper第三方插件

3.MP也内置了分页插件

如何使用

1.配置拦截器组件即可

在config的MyBatisPlusConfig.java里面配置的

    /**
      * 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
      */
     @Bean
     public MybatisPlusInterceptor mybatisPlusInterceptor() {
         MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
         interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2));
         return interceptor;
    }
 ?
     @Bean
     public ConfigurationCustomizer configurationCustomizer() {
         return configuration -> configuration.setUseDeprecatedExecutor(false);
    }

测试:

2.直接使用Page对象即可!

     //测试分页查询
     @Test
     public void testPage(){
         //参数1:当前页
         //参数2:页面大小
         //
         Page<User> page = new Page<>(2, 5);
         userMapper.selectPage(page,null);
         page.getRecords().forEach(System.out::println);
         System.out.println(page.getTotal());
    }
 ?

删除操作

基本的删除操作:

    //测试删除
     @Test
     public void testDeleteById(){
         userMapper.deleteById(1390947766875258885L);
    }
     //通过id批量删除
     @Test
     public void testDeleteBatchId(){
         userMapper.deleteBatchIds(Arrays.asList(1390947766875258882L,1390947766875258883L));
    }
     //通过map删除
     @Test
     public void testDeleteMap(){
         HashMap<String, Object> map = new HashMap<>();
         map.put("name","狂神说Java");
         userMapper.deleteByMap(map);
    }
 ?

工作中会遇到的一些问题:逻辑删除

逻辑删除

物理删除:从数据库中直接移除 相当于deleted = 1

逻辑删除:在数据库中没有被移除,而是通过一个变量来让它失效!deleted = 0类似于 => deleted = 1

管理员可以查看被删除的用户,防止数据的丢失,类似于回收站!

测试:

1.在数据表中增加一个deleted字段

技术分享图片

2.实体类中增加属性

在pojo 的 User.java中增加

 package com.kuang.pojo;
 ?
 import com.baomidou.mybatisplus.annotation.*;
 import lombok.AllArgsConstructor;
 import lombok.Data;
 import lombok.NoArgsConstructor;
 ?
 import java.util.Date;
 ?
 @Data
 @AllArgsConstructor
 @NoArgsConstructor
 public class User {
     //id是对应数据库中的主键(uuid,自增id ,雪花算法,redis,zookeeper)
     //@TableId(type = IdType.ID_WORKER)//全局唯一ID
     @TableId(type = IdType.AUTO)//自增ID
    // @TableId(type = IdType.INPUT)//手动增加ID 一旦手动输入id之后,就需要自己配置id了
     private Long id;
     private String name;
     private Integer age;
     private String email;
     @Version //乐观锁Version注解
     private Integer version;
 ?
     @TableLogic //逻辑删除
     private Integer deleted;
 ?
 ?
     //字段添加填充内容
     @TableField(fill = FieldFill.INSERT)   //字段
     private Date createTime;
     @TableField(fill = FieldFill.INSERT_UPDATE)
     private Date updateTime;
 }
 ?

3.逻辑删除。

官网地址:逻辑删除 | MyBatis-Plus (baomidou.com)

不用配置删除组件了,不用注册Bean了,官网已经没有这个配置。

在application.properties进行配置

 # 配置逻辑删除
 mybatis-plus.global-config.db-config.logic-delete-value=1
 mybatis-plus.global-config.db-config.logic-not-delete-value=0
 ?

 

技术分享图片

逻辑删除中记录还在数据库中,只是值变了:

技术分享图片

再次去查询被删除的数据时,会被自动过滤掉

技术分享图片

 

性能分析插件

我们在平时的开发中,会遇到一些慢sql。可以通过测试比如:druid....测试出来。

SQL默认有个规定:只要10秒钟没有按照规定的时间返回结果,都属于慢查询,存放到日志中

MP也提供性能分析插件,如果超过这个时间就停止运行。

MP3.2以后版本移除了性能分析插件可以通过druid执行sql的性能分析。

条件构造器

十分重要:Wrapper

我们写一些复杂的sql就可以使用它来替代!

pom.xml中的mybatis-plus-boot-starte版本换成

 <dependency>
             <groupId>com.baomidou</groupId>
             <artifactId>mybatis-plus-boot-starter</artifactId>
             <version>3.4.2</version>
         </dependency>
 ?

 

测试一:

 package com.kuang;
 ?
 import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
 import com.kuang.mapper.UserMapper;
 import com.kuang.pojo.User;
 import org.junit.jupiter.api.Test;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.boot.test.context.SpringBootTest;
 @SpringBootTest
 public class WrapperTest {
     @Autowired
     private UserMapper userMapper;
     @Test
     void contextLoads(){
         //参数是一个Wrapper 条件构造器
         //查询name不为空的用户,并且邮箱不为空的用户,年龄大于等于12
         QueryWrapper<User> wrapper = new QueryWrapper<>();
         wrapper.isNotNull("name").isNotNull("email").ge("age",12);
         userMapper.selectList(wrapper).forEach(System.out::println);//和所学习的map对比一下
 ?
 ?
    }
 }
 ?

2.测试二

 @Test
     void test2(){
         //查询名字狂神说
         QueryWrapper<User> wrapper = new QueryWrapper<>();
         wrapper.eq("name","狂神说");
         User user = userMapper.selectOne(wrapper);//查询一个数据,出现多个结果使用List或者Map
         System.out.println(user);
    }

3.测试三

    @Test
     void test3(){
         //查询年龄在20~30岁之间的用户
 ?
         QueryWrapper<User> wrapper = new QueryWrapper<>();
         wrapper.between("age",20,30);//区间
         Integer count = userMapper.selectCount(wrapper);//查询结果数
         System.out.println(count);
 ?
    }

4.测试四 模糊查询

 @Test
     void test4(){
         QueryWrapper<User> wrapper = new QueryWrapper<>();
         //查询 %e :左查询   e%:右边 %e:左边     %e% :左和右都查询
         wrapper.notLike("name","e").likeRight("email","t");
         List<Map<String, Object>> maps = userMapper.selectMaps(wrapper);
         maps.forEach(System.out::println);
 ?
 ?
    }

技术分享图片

5.测试五

  @Test
     void test5(){
         QueryWrapper<User> wrapper = new QueryWrapper<>();
        //id在子查询中查出来
         wrapper.inSql("id","select id from user where id<3");
         List<Object> objects = userMapper.selectObjs(wrapper);
         objects.forEach(System.out::println);
 ?
 ?
 ?
 ?
    }

技术分享图片

6.测试六

  @Test
     void test6(){
         QueryWrapper<User> wrapper = new QueryWrapper<>();
         //通过id进行降序Desc排序 升序排序Asc
         wrapper.orderByDesc("id");
         List<User> users = userMapper.selectList(wrapper);
         users.forEach(System.out::println);
 ?
 ?
    }

技术分享图片

代码自动生成器

AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各个模块的代码,极大的提升了开发效率。

dao pojo service controller 需要自己去编写:

类似写成这样的:

技术分享图片

技术分享图片

 #服务端口
 server.port=9000
 spring.profiles.active=dev
 #禁用模板缓存
 spring.thymeleaf.cache=false
 ?
 # mysql 8 需要增加时区配置   数据库连接配置
 spring.datasource.username=root
 spring.datasource.password=123456
 spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?useSSL=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
 # 配置日志
 mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
 # 配置逻辑删除
 mybatis-plus.global-config.db-config.logic-delete-value=1
 mybatis-plus.global-config.db-config.logic-not-delete-value=0
 ?
 ?

要生成哪个表就修改这个地方就行 strategy.setInclude("user");

 package com.kuang;
 ?
 import com.baomidou.mybatisplus.annotation.DbType;
 import com.baomidou.mybatisplus.annotation.FieldFill;
 import com.baomidou.mybatisplus.annotation.IdType;
 import com.baomidou.mybatisplus.core.config.GlobalConfig;
 import com.baomidou.mybatisplus.generator.AutoGenerator;
 import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
 import com.baomidou.mybatisplus.generator.config.PackageConfig;
 import com.baomidou.mybatisplus.generator.config.StrategyConfig;
 import com.baomidou.mybatisplus.generator.config.po.TableFill;
 import com.baomidou.mybatisplus.generator.config.rules.DateType;
 import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
 ?
 ?
 import java.util.ArrayList;
 ?
 //代码自动生成器
 public class KuangCode {
     public static void main(String[] args) {
         // 需要构建一个代码自动生成器 对象
         AutoGenerator mpg = new AutoGenerator();
 ?
 ?
         // 全局配置
         GlobalConfig gc = new GlobalConfig();
         String projectPath = System.getProperty("user.dir");
         gc.setOutputDir(projectPath+"/src/main/java");
         gc.setAuthor("狂神说");
         gc.setOpen(false);
         gc.setServiceName("%sService");//去Service的I前缀
         gc.setIdType(IdType.ID_WORKER);
         gc.setDateType(DateType.ONLY_DATE);
         gc.setSwagger2(true);
         mpg.setGlobalConfig(gc);
         //2.设置数据源的配置
         DataSourceConfig dsc = new DataSourceConfig();
         dsc.setUrl("jdbc:mysql://localhost:3306/mybatis_plus?useSSL=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8");
         dsc.setDriverName("com.mysql.cj.jdbc.Driver");
         dsc.setUsername("root");
         dsc.setPassword("123456");
         dsc.setDbType(DbType.MYSQL);
         mpg.getDataSource(dsc);
 ?
         //3.包的配置
         PackageConfig pc = new PackageConfig();
         pc.setModuleName("blog");
         pc.setParent("com.kuang");
         pc.setEntity("entity");
         pc.setMapper("mapper");
         pc.setService("service");
         pc.setController("controller");
         mpg.setPackageInfo(pc);
         // 策略配置
         StrategyConfig strategy = new StrategyConfig();
         strategy.setInclude("user");//设置要映射的表名
         strategy.setNaming(NamingStrategy.underline_to_camel);
         strategy.setColumnNaming(NamingStrategy.underline_to_camel);
         strategy.setEntityLombokModel(true);//自动生成lombok
         strategy.setLogicDeleteFieldName("deleted");//这个字段在mysql中添加
         //自动填充配置
         TableFill gmtCreate = new TableFill("gmt_create", FieldFill.INSERT);
         TableFill gmtModified = new TableFill("gmt_modified",FieldFill.INSERT_UPDATE);
         ArrayList<TableFill> tableFills = new ArrayList<>();
         tableFills.add(gmtCreate);
         tableFills.add(gmtModified);
         strategy.setTableFillList(tableFills);
         //乐观锁
         strategy.setVersionFieldName("version");
         strategy.setRestControllerStyle(true);
         strategy.setControllerMappingHyphenStyle(true);//链接请求会变成下划线命名
 ?
 ?
 ?
 ?
         mpg.setStrategy(strategy);
 ?
 ?
 ?
         mpg.execute();//执行
 ?
 ?
 ?
 ?
    }
 }
 ?

这里面的部分代码爆红,还没有找到解决办法

爆红的代码:

     PackageConfig pc = new PackageConfig();
         pc.setModuleName("blog");
         pc.setParent("com.kuang");
         pc.setEntity("entity");
         pc.setMapper("mapper");
         pc.setService("service");
         pc.setController("controller");
         mpg.setPackageInfo(pc);

B站学习网址:【狂神说Java】MyBatisPlus最新完整教程通俗易懂_哔哩哔哩 (゜-゜)つロ 干杯~-bilibili

第121天学习打卡(MyBatisPlus CRUD扩展之查询操作 分页查询 删除操作 逻辑删除 条件构造器 自动生成器 )

原文:https://www.cnblogs.com/doudoutj/p/14748892.html

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