MyBatis進(jìn)階:MyBatis-plus代碼生成器

一、MyBatis plus(簡(jiǎn)稱:mp)

1.簡(jiǎn)介:

2.使用步驟:

1.pom.xml中引入mybatis-plus-boot-starter依賴

<!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-boot-starter -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>2.2.0</version>
        </dependency>
<!-- freemarker -->
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
        </dependency>
        <!-- fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.15</version>
        </dependency>

2.application.properties文件中配置

server.port=8080
 
#mysql
spring.datasource.url=jdbc:mysql://localhost:3306/ease-run?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#mybatis-plus
mybatis-plus.mapper-locations=classpath:com/zhbit/demo/mapper/*.xml
mybatis-plus.type-aliases-package=com.zhbit.demo.domain

3.代碼生成器主類

package com.mht.springbootmybatisplus.generate;
 
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
 
/**
 * <p>
 * 代碼生成器演示
 * </p>
 */
public class MpGenerator {
 
    public static void main(String[] args) {
//        assert (false) : "代碼生成屬于危險(xiǎn)操作,請(qǐng)確定配置后取消斷言執(zhí)行代碼生成!";
        AutoGenerator mpg = new AutoGenerator();
        // 選擇 freemarker 引擎,默認(rèn) Velocity
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
 
        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        gc.setAuthor("zhbit");
        gc.setOutputDir("D://workspace/spring-boot-mybatis-plus/src/main/java");// 設(shè)置文件輸出路徑
        gc.setFileOverride(false);// 是否覆蓋同名文件,默認(rèn)是false
        gc.setActiveRecord(true);// 不需要ActiveRecord特性的請(qǐng)改為false
        gc.setEnableCache(false);// XML 二級(jí)緩存
        gc.setBaseResultMap(true);// XML ResultMap
        gc.setBaseColumnList(false);// XML columList
        /* 自定義文件命名,注意 %s 會(huì)自動(dòng)填充表實(shí)體屬性! */
        // gc.setMapperName("%sDao");
        // gc.setXmlName("%sDao");
        // gc.setServiceName("MP%sService");
        // gc.setServiceImplName("%sServiceDiy");
        // gc.setControllerName("%sAction");
        mpg.setGlobalConfig(gc);
 
        // 數(shù)據(jù)源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setDbType(DbType.MYSQL);
        dsc.setTypeConvert(new MySqlTypeConvert() {
            // 自定義數(shù)據(jù)庫(kù)表字段類型轉(zhuǎn)換【可選】
            @Override
            public DbColumnType processTypeConvert(String fieldType) {
                System.out.println("轉(zhuǎn)換類型:" + fieldType);
                // 注意??!processTypeConvert 存在默認(rèn)類型轉(zhuǎn)換,如果不是你要的效果請(qǐng)自定義返回、非如下直接返回。
                return super.processTypeConvert(fieldType);
            }
        });
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("root");
        dsc.setUrl("jdbc:mysql://localhost:3306/ease-run?useUnicode=true&characterEncoding=utf8");
        mpg.setDataSource(dsc);
 
        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        // strategy.setCapitalMode(true);// 全局大寫(xiě)命名 ORACLE 注意
        strategy.setTablePrefix(new String[] { "user_" });// 此處可以修改為您的表前綴
        strategy.setNaming(NamingStrategy.nochange);// 表名生成策略
        strategy.setInclude(new String[] { "user" }); // 需要生成的表
        // strategy.setExclude(new String[]{"test"}); // 排除生成的表
        // 自定義實(shí)體父類
        // strategy.setSuperEntityClass("com.baomidou.demo.TestEntity");
        // 自定義實(shí)體,公共字段
        // strategy.setSuperEntityColumns(new String[] { "test_id", "age" });
        // 自定義 mapper 父類
        // strategy.setSuperMapperClass("com.baomidou.demo.TestMapper");
        // 自定義 service 父類
        // strategy.setSuperServiceClass("com.baomidou.demo.TestService");
        // 自定義 service 實(shí)現(xiàn)類父類
        // strategy.setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl");
        // 自定義 controller 父類
        // strategy.setSuperControllerClass("com.baomidou.demo.TestController");
        // 【實(shí)體】是否生成字段常量(默認(rèn) false)
        // public static final String ID = "test_id";
        // strategy.setEntityColumnConstant(true);
        // 【實(shí)體】是否為構(gòu)建者模型(默認(rèn) false)
        // public User setName(String name) {this.name = name; return this;}
        // strategy.setEntityBuilderModel(true);
        mpg.setStrategy(strategy);
 
        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent("com.mht.springbootmybatisplus");
        // pc.setModuleName("test");
        mpg.setPackageInfo(pc);
 
        // 注入自定義配置,可以在 VM 中使用 cfg.abc 【可無(wú)】
        // InjectionConfig cfg = new InjectionConfig() {
        // @Override
        // public void initMap() {
        // Map<String, Object> map = new HashMap<String, Object>();
        // map.put("abc", this.getConfig().getGlobalConfig().getAuthor() +
        // "-mp");
        // this.setMap(map);
        // }
        // };
        //
        // // 自定義 xxList.jsp 生成
        // List<FileOutConfig> focList = new ArrayList<>();
        // focList.add(new FileOutConfig("/template/list.jsp.vm") {
        // @Override
        // public String outputFile(TableInfo tableInfo) {
        // // 自定義輸入文件名稱
        // return "D://my_" + tableInfo.getEntityName() + ".jsp";
        // }
        // });
        // cfg.setFileOutConfigList(focList);
        // mpg.setCfg(cfg);
        //
        // // 調(diào)整 xml 生成目錄演示
        // focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
        // @Override
        // public String outputFile(TableInfo tableInfo) {
        // return "/develop/code/xml/" + tableInfo.getEntityName() + ".xml";
        // }
        // });
        // cfg.setFileOutConfigList(focList);
        // mpg.setCfg(cfg);
        //
        // // 關(guān)閉默認(rèn) xml 生成,調(diào)整生成 至 根目錄
        // TemplateConfig tc = new TemplateConfig();
        // tc.setXml(null);
        // mpg.setTemplate(tc);
 
        // 自定義模板配置,可以 copy 源碼 mybatis-plus/src/main/resources/templates 下面內(nèi)容修改,
        // 放置自己項(xiàng)目的 src/main/resources/templates 目錄下, 默認(rèn)名稱一下可以不配置,也可以自定義模板名稱
        // TemplateConfig tc = new TemplateConfig();
        // tc.setController("...");
        // tc.setEntity("...");
        // tc.setMapper("...");
        // tc.setXml("...");
        // tc.setService("...");
        // tc.setServiceImpl("...");
        // 如上任何一個(gè)模塊如果設(shè)置 空 OR Null 將不生成該模塊。
        // mpg.setTemplate(tc);
 
        // 執(zhí)行生成
        mpg.execute();
 
        // 打印注入設(shè)置(可選)
        // System.err.println(mpg.getCfg().getMap().get("abc"));
    }
}

說(shuō)明:gc.setOutputDir("D://workspace/spring-boot-mybatis/src/main/java");// 設(shè)置文件輸出路徑;
pc.setParent("com.mht.springbootmybatis");// 父包名


代碼生成器存放位置參考.png

至此,執(zhí)行main方法就可生成所需要的ORM代碼了。
注意:
使用代碼時(shí),一定記得在spring boot項(xiàng)目中添加mybatis的包掃描路徑,或@Mapper注解:

@SpringBootApplication
@MapperScan("com.mht.springbootmybatisplus.mapper")
public class SpringBootMybatisPlusApplication {
    private static final Logger logger = LoggerFactory.getLogger(SpringBootMybatisPlusApplication.class);
 
    public static void main(String[] args) {
        SpringApplication.run(SpringBootMybatisPlusApplication.class, args);
        logger.info("========================啟動(dòng)完畢========================");
    }
}

或者

@Mapper
public interface UserMapper extends BaseMapper<User> {
}

二、其他可視化代碼生成器

1.auto-code-ui-spring-boot

1.在pox.xml中引入依賴

<!-- 代碼生成器可視化視圖 -->
<dependency>
    <groupId>com.zengtengpeng</groupId>
    <artifactId>auto-code-ui-spring-boot-starter</artifactId>
    <version>1.0.1</version>
</dependency>

2.application.properties增加屬性配置

#pagehelper插件
pagehelper.helperDialect=mysql
pagehelper.reasonable=true
pagehelper.supportMethodsArguments=true
pagehelper.params=count=countSql

#代碼生成器配置
#生成代碼的項(xiàng)目根路徑
auto-code.parentPath=E:\\resource\\workspaceJDB\\auto-code-springboot-demo
#生成代碼的父包 如父包是com.zengtengpeng.test  controller將在com.zengtengpeng.test.controller下 bean 將在com.zengtengpeng.test.bean下 ,service,dao同理
auto-code.parentPack=com.zengtengpeng.simple

3.啟動(dòng)訪問(wèn)可視化代碼生成器

http://localhost:8080/auto-code-ui/ui/index.html

更多可參考:https://gitee.com/ztp/auto-code#3

參考:https://www.oschina.net/p/auto-code-ui-spring-boot-starter

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容