1. 程式人生 > 其它 >使用MyBatis-plus自動生成程式碼

使用MyBatis-plus自動生成程式碼

使用使用MyBatis-plus可以快速生成程式碼,讓你脫離建包的痛苦

直接上一個我經常使用的程式碼:

public class CodeGenerator {

  @Test
  public void getCode() {
    // 1、建立程式碼生成器
    AutoGenerator mpg = new AutoGenerator();
      
    // 2、全域性配置
    GlobalConfig gc = new GlobalConfig();
    /*
    String projectPath = System.getProperty("user.dir");
    System.out.println(projectPath);
    
*/ gc.setOutputDir("D:\\tools\\maven_project\\blb_parent\\service\\service_edu" + "/src/main/java");//1.修改為你專案的目錄 gc.setAuthor("zf"); gc.setOpen(false); //生成後是否開啟資源管理器 gc.setFileOverride(false); //重新生成時檔案是否覆蓋 /* * mp生成service層程式碼,預設介面名稱第一個字母有I * UcenterService * */ gc.setServiceName(
"%sService"); //去掉Service介面的首字母I gc.setIdType(IdType.ASSIGN_ID); //主鍵策略 gc.setDateType(DateType.ONLY_DATE);//定義生成的實體類中日期型別 gc.setSwagger2(true);//開啟Swagger2模式 mpg.setGlobalConfig(gc); // 3、資料來源配置 DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl("jdbc:mysql://localhost:3306/blb_edu
?serverTimezone=GMT%2B8");//2.修改為你資料庫的名字,使用者名稱,密碼 dsc.setDriverName("com.mysql.cj.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("root"); dsc.setDbType(DbType.MYSQL); mpg.setDataSource(dsc); // 4、包配置 PackageConfig pc = new PackageConfig(); pc.setModuleName("edu"); //模組名 pc.setParent("cn.zf.service"); pc.setController("controller"); pc.setEntity("entity"); pc.setService("service"); pc.setMapper("mapper"); mpg.setPackageInfo(pc); // 5、策略配置 StrategyConfig strategy = new StrategyConfig(); //strategy.setInclude("edu_teacher"); strategy.setNaming(NamingStrategy.underline_to_camel);//資料庫表對映到實體的命名策略 strategy.setTablePrefix(pc.getModuleName() + "_"); //生成實體時去掉表字首 // 資料庫表字段對映到實體的命名策略 strategy.setColumnNaming(NamingStrategy.underline_to_camel); // lombok 模型 @Accessors(chain = true) setter鏈式操作 strategy.setEntityLombokModel(true); strategy.setLogicDeleteFieldName("is_deleted"); // 3.修改邏輯刪除欄位名 strategy.setEntityBooleanColumnRemoveIsPrefix(true); //去掉布林值is_字首 strategy.setRestControllerStyle(true); //restful api風格控制器 strategy.setControllerMappingHyphenStyle(true); //url中駝峰轉連字元 // 4.修改自動填充欄位名 TableFill gmtCreate = new TableFill("gmt_create", FieldFill.INSERT); TableFill gmtModified = new TableFill("gmt_modified", FieldFill.INSERT_UPDATE); ArrayList<TableFill> tableFills = new ArrayList<>(); tableFills.add(gmtCreate); tableFills.add(gmtModified); strategy.setTableFillList(tableFills); mpg.setStrategy(strategy); // 6、執行 mpg.execute(); } }

通常的使用,修改以上地方就行了

成果圖: