MyBatis Plus(八)

代码生成器

  1. AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各个模块的代码

添加代码生成器的依赖

  1. MyBatis-Plus 从 3.0.3 之后移除了代码生成器与模板引擎的默认依赖,需要手动添加相关依赖
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.4.0</version>
</dependency>
  1. 添加模板引擎依赖,MyBatis-Plus 支持 Velocity(默认)、Freemarker、Beetl,用户可以选择自己熟悉的模板引,同时可以采用自定义模板引擎。

代码生成器的模板引擎

  1. Velocity(默认)
<dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity-engine-core</artifactId>
    <version>2.2</version>
</dependency>
  1. Freemarker模板引擎
<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.30</version>
</dependency>
  1. Beetl模板引擎
<dependency>
    <groupId>com.ibeetl</groupId>
    <artifactId>beetl</artifactId>
    <version>3.2.1.RELEASE</version>
</dependency>
  1. 如果选择了非默认引擎,需要在 AutoGenerator 中 设置模板引擎。
AutoGenerator generator = new AutoGenerator();
// set freemarker engine
generator.setTemplateEngine(new FreemarkerTemplateEngine());
// set beetl engine
generator.setTemplateEngine(new BeetlTemplateEngine());
// set custom engine (reference class is your custom engine class)
generator.setTemplateEngine(new CustomTemplateEngine());
// other config
...

代码生成器样例

  1. 使用 FreeMarker 作为代码生成器的模板引擎,添加如下依赖
<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.30</version>
</dependency>
  1. 将生成“user”数据表的 controller、mapper、entity、service 代码
public class MysqlGenerator {
    
    
 
    public static void main(String[] args) {
    
    
        String userDir = System.getProperty("user.dir");
        System.out.println("userDir=" + userDir);
 
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();
 
        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/mybatis-plus-learn/src/main/java");
        gc.setAuthor("ryx"); // 作者名称
        gc.setBaseResultMap(true); // mapper.xml 生成 ResultMap
        gc.setBaseColumnList(true); // mapper.xml 生成 ColumnList
        gc.setOpen(false);
        mpg.setGlobalConfig(gc);
 
        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/mybatis_test?useSSL=false");
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("aaaaaa");
        mpg.setDataSource(dsc);
 
        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent("com.hxstrive.mybatis.auto");
        mpg.setPackageInfo(pc);
 
        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();
        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);
 
        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        strategy.setInclude("user");
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }
 
}

MyBatis Plus(分页)

  1. 在 MyBatis Plus 中,可以通过 PaginationInnerInterceptor 插件快速实现分页

  2. 在 Spring Boot 中,使用 @Configuration 和 @Bean 注解配置分页插件

    @Bean
    public MybatisPlusInterceptor paginationInterceptor() {
          
          
    MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
    // 分页插件,如果不配置,分页插件将不生效
    // 指定数据库方言为 MYSQL
    interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
    return interceptor;
    }
    
  3. PaginationInnerInterceptor 分页插件的属性

    1. overflow:溢出总页数后是否进行处理,默认不处理。参见插件 continuePage 方法
    2. maxLimit:单页分页条数限制,默认无限制。参见插件 handlerLimit 方法
    3. dbType:数据库类型(可取值见 DbType 枚举类型),根据类型获取应使用的分页方言。参见插件 findIDialect 方法
    4. dialect:方言实现类,需要实现 IDialect 接口。参见插件 findIDialect 方法

MyBatis Plus(分页)样例

  1. 配置分页插件 PaginationInnerInterceptor

    @Configuration
    public class MybatisPlusConfig {
          
          
     
        @Autowired
        private TenantIdManager tenantIdManager;
     
        @Bean
        public MybatisPlusInterceptor paginationInterceptor() {
          
          
            MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
            // 分页插件,如果不配置,分页插件将不生效
            // 指定数据库方言为 MYSQL
            PaginationInnerInterceptor pageInterceptor = new PaginationInnerInterceptor(DbType.MYSQL);
            pageInterceptor.setMaxLimit(20L); // 单页分页条数限制
            interceptor.addInnerInterceptor(pageInterceptor);
            return interceptor;
        }
     
    }
    
  2. ,查询用户列表的第二页,每页 30 条数据,但是只查询出了20条数据。这是因为配置分页插件时指定了 MaxLimit

    @RunWith(SpringRunner.class)
    @SpringBootTest
    class PluginDemo3 {
          
          
     
        @Autowired
        private SimpleMapper mapper;
     
        @Test
        void contextLoads() {
          
          
            // 如果 page 指定的 pageSize 大于 MaxLimit,则使用 MaxLimit 作为 pageSize
            Page<UserBean> page = new Page<>(2 /* pageNum */, 30 /* pageSize */);
            mapper.selectPage(page, null);
            for(UserBean userBean : page.getRecords()) {
          
          
                System.out.println(userBean);
            }
        }
     
    }
    

防止全表更新与删除

  1. MyBatis Plus 有防止不小心或者有人恶意将整个表格的数据修改、或删除的插件。
  2. MyBatis Plus 提供了 BlockAttackInnerInterceptor 插件,该插件可以阻止全表更新和删除操作。在一定程度上,保证了数据库数据的安全

插件配置

  1. 使用 @Configuration 和 @Bean 注解配置 BlockAttackInnerInterceptor 插件,

    package com.hxstrive.mybatis_plus;
     
    import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
    import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
     
    @Configuration
    public class MybatisPlusConfig {
          
          
        @Bean
        public MybatisPlusInterceptor paginationInterceptor() {
          
          
            MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
            // 防止全表更新与删除
            // 针对 update 和 delete 语句
            interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());
            return interceptor;
        }
    }
    
  2. 定义一个 SimpleMapper 接口继承 BaseMapper 接口

    public interface SimpleMapper extends BaseMapper<UserBean> {
          
          
     
    }
    
  3. 使用 @SpringBootTest 和 @RunWith 注解,实现一个简单的单元测试。验证 BlockAttackInnerInterceptor 插件功能

    @RunWith(SpringRunner.class)
    @SpringBootTest
    class PluginDemo {
          
          
        @Autowired
        private SimpleMapper mapper;
     
        @Test
        void contextLoads() {
          
          
            // 更新全表数据
            UpdateWrapper<UserBean> wrapper = new UpdateWrapper<>();
     
            UserBean userBean = new UserBean();
            userBean.setFace(new byte[]{
          
          });
     
            int result = mapper.update(userBean, wrapper);
            System.out.println("result=" + result);
        }
     
    }
    
  4. 运行上面代码,将抛出如下错误信息

    org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.PersistenceException: 
    ### Error updating database.  Cause: com.baomidou.mybatisplus.core.exceptions.MybatisPlusException: Prohibition of table update operation
    ### The error may exist in com/hxstrive/mybatis_plus/mapper/SimpleMapper.java (best guess)
    ### The error may involve com.hxstrive.mybatis_plus.mapper.SimpleMapper.update
    ### The error occurred while executing an update
    ### Cause: com.baomidou.mybatisplus.core.exceptions.MybatisPlusException: Prohibition of table update operation
    at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:92)
    at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:440)
    at com.sun.proxy.$Proxy63.update(Unknown Source)
    ...
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
    Caused by: org.apache.ibatis.exceptions.PersistenceException:
    
  5. “Prohibition of table update operation” 表示禁止全表更新操作,这样就能阻止全表更新和删除操作。

猜你喜欢

转载自blog.csdn.net/qq_43408367/article/details/121482987
今日推荐