天天看點

mybatis-plus代碼生成器 localdatetime 指定時間類型

自動生成代碼

public class GeneratorCodeConfig {
    private static final String URL = "jdbc:mysql://127.0.0.1:3306/kyx?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "123456";

    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("請輸入" + tip + ":");
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotEmpty(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("xyang");
        gc.setOpen(false);
        //實體屬性 Swagger2 注解
        gc.setSwagger2(false);
        gc.setActiveRecord(true);
        // XML 二級緩存
        gc.setEnableCache(false);
        // XML ResultMap
        gc.setBaseResultMap(true);
        // XML columList
        gc.setBaseColumnList(true);
        // 指定生成日期類型
		// gc.setDateType(DateType.ONLY_DATE);
        mpg.setGlobalConfig(gc);

        // 資料源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(URL);
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername(USERNAME);
        dsc.setPassword(PASSWORD);
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(scanner("子產品名"));
        pc.setParent("com.kyx.orderSys.biz");
        pc.setEntity("model");
        pc.setMapper("mapper");
        pc.setService("service");
        pc.setServiceImpl("service.impl");
        mpg.setPackageInfo(pc);

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

        // 如果模闆引擎是 freemarker
        String templatePath = "/templates/mapper.xml.ftl";
        // 如果模闆引擎是 velocity
        // String templatePath = "/templates/mapper.xml.vm";

        // 自定義輸出配置
        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();

        // 配置自定義輸出模闆
        //指定自定義模闆路徑,注意不要帶上.ftl/.vm, 會根據使用的模闆引擎自動識别
        // templateConfig.setEntity("templates/entity.java");
        // templateConfig.setService();
        // templateConfig.setController();

        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);

        // 政策配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setSuperEntityClass(Model.class);
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);

        strategy.setEntityLombokModel(true);
        // 公共父類
        strategy.setSuperControllerClass(BaseController.class);
        // 寫于父類中的公共字段
        // strategy.setSuperEntityColumns("id");
        String[] split = scanner("表名,多個英文逗号分割").split(",");
        strategy.setInclude(Arrays.stream(split).map(i -> pc.getModuleName() + "_" + i).toArray(String[]::new));
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }
}
           

預設生成日期格式為 LocalDateTime 和 LocalDate

@Data
@EqualsAndHashCode(callSuper = true)
@TableName("sys_user")
public class User extends Model<User> {

    private static final long serialVersionUID = 1L;

    @TableId(value = "id", type = IdType.AUTO)
    private Long id;

    /**
     * 建立時間
     */
    private LocalDateTime createTime;

    /**
     * 是否删除
     */
    private Boolean deleted;

    /**
     * 更新時間
     */
    private LocalDateTime updateTime;

}
           
可在 GeneratorCodeConfig 類中添加設定 gc.setDateType(DateType.ONLY_DATE); 已實作 Date 類型. 添加後生成的實體類如下所示
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("sys_user")
public class User extends Model<User> {

    private static final long serialVersionUID = 1L;

    @TableId(value = "id", type = IdType.AUTO)
    private Long id;

    /**
     * 建立時間
     */
    private Date createTime;

    /**
     * 是否删除
     */
    private Boolean deleted;

    /**
     * 更新時間
     */
    private Date updateTime;

}
           
可添加注解來實作前後端日期格式的轉換
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("sys_user")
public class User extends Model<User> {

    private static final long serialVersionUID = 1L;

    @TableId(value = "id", type = IdType.AUTO)
    private Long id;

    /**
     * 建立時間
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone="GMT+8")
    private Date createTime;

    /**
     * 是否删除
     */
    private Boolean deleted;

    /**
     * 更新時間
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone="GMT+8")
    private Date updateTime;

}