Mybatis-plus学习2

一、Mybatis-plus分页操作

        1.配置拦截器即可

    //分页插件
    @Bean
    public PaginationInterceptor paginationInterceptor(){
        return new PaginationInterceptor();
    }

        2.直接使用Page对象

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

二、Mybatis-plus逻辑删除

物理删除:从数据库中直接移除

逻辑删除:在数据库中没有直接移除,而是通过一个变量来让数据失效,就是把变量的值从0变为1。

管理员可以查看删除的数据,为了防止数据的丢失,与垃圾回收站相似!

        1.在数据表中加入一个delete字段

        2. 完善实体类

@Data
public class User {
    @TableId(type = IdType.AUTO)//设置主键自增
    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)
    //INSERT:插入和更新的时候自动填充
    private Date gmtCreate;
    @TableField(fill = FieldFill.INSERT_UPDATE)
    //INSERT_UPDATE:插入和更新的时候自动填充
    private Date gmtModifed;
}

        3.添加逻辑删除组件

    //逻辑删除组件
    @Bean
    public ISqlInjector sqlInjector(){
        return new LogicSqlInjector();
    }

        4.配置逻辑删除组件

#配置逻辑组件
#没有删除的值为0
#有删除的值为1
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0

        5.删除测试

    @Test
    public void testDelete1(){
        userMapper.deleteById( (long)5 );
    }

 从图可以知道执行删除操作实际上是执行更新操作

当我们再次查询id为5的用户时,它是查询不到的。

    //测试单个查询
    @Test
    public void testSelectById(){
        User user = userMapper.selectById( 5 );
        System.out.println(user);
    }

三、性能分析插件

 在开发中,我们会遇到一些慢sql。我们是通过测试、druid或者其他一些测试工具把它们给揪出来。但是Mybatis-plus有一个性能分析插件,如果超过某个时间就会停止运行!

扫描二维码关注公众号,回复: 14783196 查看本文章

作用:设置性能分析拦截器,用于输出每一条SQL语句及其时间!

         1.设置性能分析拦截器

    //性能分析拦截器
    @Bean
    @Profile( {"dev","test"} ) //设置dev,test环境开启,只有在开发和测试环境中开启,保证我们的效率
    public PerformanceInterceptor performanceInterceptor(){
        PerformanceInterceptor interceptor = new PerformanceInterceptor();
        interceptor.setMaxTime(100);//设置sql执行的最大时间,如果超过了这个时间则不执行,单位 毫秒
        interceptor.setFormat(true);//是否开启格式化代码
        return interceptor;
    }

        2.在application.properties中设置配置环境

#设置开发环境
spring.profiles.active=dev

        3.测试使用

    //查询所有用户
    @Test
    void contextLoads() {
        //参数是一个wrapper,它是一个条件构造器
        List<User> users = userMapper.selectList(null);
        users.forEach( System.out::println );
    }

 只要超过设置的最大时间就会报错!

四、条件构造器

条件构造器(Wrapper)在mybatis-plus中十分的重要,我们在写一些复杂的sql语句就可以使用它来代替。

第一个测试:

    @Test
    void contextLoads() {
        //查询name不为空的用户,且邮箱不为空的用户,年龄大于等于18岁的
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.isNotNull( "name" ).isNotNull( "email" ).ge( "age",15 );
        List<User> users = userMapper.selectList( wrapper );
        users.forEach( System.out::println );
    }

 第二个测试:

    @Test
    void testWrapper(){
        //查询名字为来一沓java
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq( "name","来一沓java" );
        User user = userMapper.selectOne( wrapper );
        System.out.println(user);
    }

 第三个测试:

    @Test
    void testWrapper2(){
        //查询年龄在20~30之间得用户
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.between( "age",15,18 );
        Integer count = userMapper.selectCount( wrapper );
        System.out.println(count);
    }

 第四个测试:

    @Test
    void testWrapper3(){
        //模糊查询
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper
                .notLike( "name","来" )//名字中不包含 来 
                .likeRight( "email","p" );//邮箱中右边是 p 开头的
        List<Map<String, Object>> maps = userMapper.selectMaps( wrapper );
        maps.forEach( System.out::println );
    }

 第五个测试:

    @Test
    void testWrapper4(){
        //模糊查询
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        //id是在子查询中查出来的
        wrapper.inSql( "id","select id from user where id >7" );//在子查询中查出id大于7的用户
        List<Object> objects = userMapper.selectObjs( wrapper );
        objects.forEach( System.out::println );
    }

第六个测试:

    @Test
    void testWrapper5(){
        //通过创建时间的先后排序
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc( "gmt_create" );
        List<User> users = userMapper.selectList( wrapper );
        users.forEach( System.out::println );
    }

更多的测试请移步 条件构造器 | MyBatis-Plus (baomidou.com)

 五、代码生成器

顾名思义就是让程序帮我们把dao层,pojo层、service层、controller层的代码全部完成!

         1.导入模板引擎

<!--        mybatis-plus,它是自己开发的,非官方的-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.0.5</version>
        </dependency>
        <!-- 模板引擎 -->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.0</version>
        </dependency>

        2.编写代码生成器CodeGenerator.java

//代码生成器
public class CodeGenerator {
    public static void main(String[] args) {
        //需要构建一个代码自动生成器  对象
        AutoGenerator mpg = new AutoGenerator();
        //配置策略

        //全局配置
        GlobalConfig config = new GlobalConfig();
        String projectPath = System.getProperty( "user.dir" );//获取当前项目目录
        config.setOutputDir( projectPath+"/src/main/java" );
        config.setAuthor( "RenXianJun" );//设置作者
        config.setOpen( false );//是否打开资源管理器
        config.setFileOverride( false );//是否覆盖之前生成的
        config.setServiceName( "%sService" );//去除Service的I前缀
        config.setIdType( IdType.ID_WORKER );//设置主键生成策略
        config.setDateType( DateType.ONLY_DATE );//设置日期的类型
        config.setSwagger2( true );//设置自动配置Swagger文档
        mpg.setGlobalConfig( config );//把全局配置放到生成器中

        //设置数据源
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&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.setDataSource(dsc);

        //设置包的配置,就是这些包放在那个位置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName("user");//设置模块名
        pc.setParent("com.rxj");//设置生成的类放在哪一个包下
        pc.setEntity( "entity" );//设置实体类的名字
        pc.setMapper( "mapper" );//设置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" );//设置逻辑删除的名字

        //设置自动填充配置
        TableFill gmtCreate = new TableFill( "gmt_create", FieldFill.INSERT );
        TableFill gmtModifed = new TableFill( "gmt_modifed", FieldFill.INSERT_UPDATE );
        ArrayList<TableFill> list = new ArrayList<>();
        list.add( gmtCreate );
        list.add( gmtModifed );
        strategy.setTableFillList( list );//设置自动填充策略

        //乐观锁的配置
        strategy.setVersionFieldName( "version" );

        //设置驼峰命名
        strategy.setRestControllerStyle( true );

        //设置controller里面的一些字段
        strategy.setControllerMappingHyphenStyle( true );

        mpg.setStrategy( strategy );

        mpg.execute();//执行
    }
}

猜你喜欢

转载自blog.csdn.net/qq_52146944/article/details/130014072