[筆記]SpringBoot中使用MyBatis Plus Generator


Mybatis Plus是基於Mybatis進行改良的框架,提高了使用Mybatis框架進行數據庫操作的效率,並能夠使用生成器快速生成表對應的CURD Service類以及數據庫實體類類,生成的實體類支持Lombok注解,非常簡潔,且支持原生的Mybatis Mapper操作。

Mybatis框架雖然也有代碼生成器,能夠根據表生成對應的Example條件構造器從而進行數據庫操作,但生成的實體類除了表字段外還充斥着其他代碼,個人感覺不太喜歡,一個表實體類除了字段外,還充斥着其他大量代碼,看起來太難受了(狗頭

此文僅作為記錄使用Mybatis Plus Generator生成代碼的相關配置和操作

 

pom依賴:

        <!--MyBatis Plus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.0</version>
        </dependency>
            <!--MyBatis Plus代碼生成相關依賴-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.3.0</version>
        </dependency>
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.29</version>
        </dependency>
        <dependency>
            <groupId>com.ibeetl</groupId>
            <artifactId>beetl</artifactId>
            <version>3.0.15.RELEASE</version>
        </dependency>    

在SpringBoot項目的resouce目錄添加MyBatisPlusGenerator.properties配置文件:

generator.jdbc.url=jdbc:mysql://127.0.0.1:3306/mydb?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai
generator.jdbc.driver=com.mysql.cj.jdbc.Driver
generator.jdbc.username=root
generator.jdbc.password=pwd

代碼生成:

public class MyBatisPlusGenerator {

    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"); // 生成文件的輸出目錄,默認D根目錄
        gc.setFileOverride(true); // 是否覆蓋已有文件
        gc.setAuthor("ahrenJ");
        gc.setOpen(false); // 是否打開輸出目錄,默認true
        gc.setEnableCache(false); // 是否在xml中添加二級緩存配置,默認false
        gc.setSwagger2(false); // 開啟 swagger2 模式,默認false

        gc.setEntityName("%sModel");
        gc.setMapperName("%sMapper");
        gc.setXmlName("%sMapper");
        gc.setServiceName("I%sService");
        gc.setServiceImplName("%sServiceImpl");
        mpg.setGlobalConfig(gc);

        // 數據源配置
        DataSourceConfig dsc = new DataSourceConfig();
        Properties properties = new Properties();
        try {
            File file = new ClassPathResource("/MyBatisPlusGenerator.properties").getFile();
            properties.load(new FileInputStream(file));
            dsc.setUrl(properties.getProperty("generator.jdbc.url"));
            dsc.setSchemaName("databaseName");
            dsc.setDriverName(properties.getProperty("generator.jdbc.driver"));
            dsc.setUsername(properties.getProperty("generator.jdbc.username"));
            dsc.setPassword(properties.getProperty("generator.jdbc.password"));
            mpg.setDataSource(dsc);
        } catch (IOException e) {
            throw new RuntimeException("數據源配置錯誤", e);
        }

        // 包名配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName("taoism");
        pc.setParent("com.music");
        pc.setEntity("model");
        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) {
                // 自定義輸出文件名
                return projectPath + "/taoism-db/src/main/resources/mapper/"
                        + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();
        // 配置自定義輸出模板
        // templateConfig.setEntity();
        // templateConfig.setService();
        templateConfig.setController(null);
        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel); // 數據庫表映射到實體的命名策略
        strategy.setColumnNaming(NamingStrategy.underline_to_camel); // 數據庫表字段映射到實體的命名策略, 未指定按照 naming 執行
        //strategy.setSuperEntityClass("com.shiyu.BaseEntity"); //自定義繼承的Entity類全稱,帶包名
        //strategy.setSuperEntityColumns(new String[] {"id","gmtCreate","gmtModified"});// 自定義基礎的Entity類,公共字段
        strategy.setEntityLombokModel(true); // 是否為lombok模型
        strategy.setEntityBooleanColumnRemoveIsPrefix(true); // Boolean類型字段是否移除is前綴
        strategy.setRestControllerStyle(false); // 生成 @RestController 控制器,個人覺得有點多余
        //strategy.setSuperControllerClass("com.music.taosim.ant.common.BaseController");
     //startegy.setInclude("tableName"); 當對某張表有所改動但只想重新生成這張表,可以這樣設置
strategy.setControllerMappingHyphenStyle(true); // 駝峰轉連字符 如 umps_user 變為 upms/user // strategy.setTablePrefix(pc.getModuleName() + "_"); // 表前綴 mpg.setStrategy(strategy); mpg.setTemplateEngine(new FreemarkerTemplateEngine()); //設置模板引擎類型,默認為 velocity mpg.execute(); } }

執行main方法,即可生成


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM