實戰代碼(十三):Springboot集成Mybatis-Plus

一、理論基礎

MyBatis-Plus 是MyBatis的增強工具,配合Lombok,可以極大的減少代碼量、提升開發效率。

Mybatis-Plus的文檔介紹很詳細,這裏只說下個人的使用感受

  • 使用簡單,少量的操作便可以完成CRUD的全部工作,可以讓人把絕大部分精力放在業務邏輯上。
  • 多數據源管理、分頁插件等常用的功能都支持的很好
  • 代碼生成器簡單好用,可以極爲快速的實現CRUD
  • 官方文檔更新及時,而且極爲詳細,根據文檔可以很容易的實現一個demo,本文完全是按照文檔做的小demo。
  • 有着完善的示例代碼,各種常用的功能都能找到官方的示例


官方文檔
官方示例代碼

二、實戰代碼

2.1 依賴引入

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.4.1</version>
</dependency>
<!-- mybatis plus 代碼生成器 -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.4.1</version>
</dependency>
<!-- mybatisplus 代碼生成器模板 -->
<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.30</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

2.2 配置文件

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/spring-boot-demo?useSSL=false
    username: root
    password: yang2020

2.3 分頁插件配置

@Configuration
@MapperScan("com.smile.demo.mybatisplus.demo.mapper")
public class MybatisPlusConfig {


    /**
     * 新的分頁插件,一緩和二緩遵循mybatis的規則,需要設置 MybatisConfiguration#useDeprecatedExecutor = false 避免緩存出現問題
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }


    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
        return configuration -> configuration.setUseDeprecatedExecutor(false);
    }
}

2.4 代碼生成器

/**
 * mybatis plus代碼生成器
 * - 官方文檔地址:https://mybatis.plus/guide/generator.html#使用教程
 */
public class CodeGenerator {

    private static final String ROOT_PACKAGE = "com.smile.demo.mybatisplus";
    private static final String AUTHOR = "Smile";
    private static final String DB_URL = "jdbc:mysql://127.0.0.1:3306/spring-boot-demo?useUnicode=true&useSSL=false&characterEncoding=utf8";
    private static final String DB_DRIVER_NAME = "com.mysql.cj.jdbc.Driver";
    private static final String DB_USERNAME = "root";
    private static final String DB_PASSWORD = "yang2020";

    /**
     * <p>
     * 讀取控制檯內容
     * </p>
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("請輸入" + tip + ":");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotBlank(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("請輸入正確的" + tip + "!");
    }

    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(AUTHOR);
        gc.setOpen(false);
        mpg.setGlobalConfig(gc);

        // 數據源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(DB_URL);
        dsc.setDriverName(DB_DRIVER_NAME);
        dsc.setUsername(DB_USERNAME);
        dsc.setPassword(DB_PASSWORD);
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(scanner("包名"));
        pc.setParent(ROOT_PACKAGE);
        mpg.setPackageInfo(pc);

        // 自定義配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };

        // 模板引擎是 freemarker
        String templatePath = "/templates/mapper.xml.ftl";

        // 自定義輸出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定義配置會被優先輸出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定義輸出文件名 , 如果你 Entity 設置了前後綴、此處注意 xml 的名稱會跟着發生變化!!
                return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 配置模板
        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(scanner("表名,多個英文逗號分割").split(","));
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }

}

2.5 簡單的示例

全部源碼見GitHub,點擊進入

// 分頁
super.page(new Page<>(pageNo, pageSize))
// 根據參數讀取單條數據
UserInfo userInfo = super.getOne(new QueryWrapper<UserInfo>().lambda().eq(UserInfo::getId, userId));

2.6 條件構造器

詳見官方文檔

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章