mybatis-plus code generator demo

code generator 代碼生成器主程序

// 主生成程序
public class MybatisGenerator {

    public static final String url = "jdbc:mysql://localhost:3306/user?useUnicode=true&characterEncoding=utf-8&useSSL=false&allowMultiQueries=true";
    public static final String userName = "root";
    public static final String userPassword = "123456";

    public static final String projectPath = "C:/work/demo/mybatis-plus-demo";

    public static void main(String[] args) {


        DataSourceConfig dataSourceConfig =
                new DataSourceConfig.Builder(url, userName, userPassword).build();

        AutoGenerator generator = new AutoGenerator(dataSourceConfig);


        GlobalConfig globalConfig = new GlobalConfig.Builder().openDir(false).
                fileOverride().
                outputDir(projectPath + "/src/main/java").
                author("your name").
                build();

        generator.global(globalConfig);

      // 各個文件生成位置
        PackageConfig packageConfig = new PackageConfig.Builder().
                parent("com.org.example").
                service("manager").
                serviceImpl("manager.impl").
                entity("domain.entity").
                mapper("dao.mapper").
                build();
        generator.packageInfo(packageConfig);

        // 策略没咙,指定生成表等基本信息
        StrategyConfig strategy = new StrategyConfig.Builder().
                addInclude(new String[]{"user_address"}).
                build();
        
        // 設(shè)置service 的名字模板
        Service.Builder serviceBuilder = strategy.serviceBuilder();
        serviceBuilder.formatServiceFileName("%sManager").formatServiceImplFileName("%sManagerImpl");
        
        // 設(shè)置生成的entity 模板
        Entity.Builder entityBuilder = strategy.entityBuilder();
        entityBuilder.enableLombok().columnNaming(underline_to_camel).
                naming(underline_to_camel);

        
        generator.strategy(strategy);
        
        // 基本模板配置
        TemplateConfig templateConfig = new TemplateConfig.Builder().
                disable(TemplateType.XML, TemplateType.CONTROLLER).
                build();
        generator.template(templateConfig);

        // 執(zhí)行
        generator.execute();

    }
}

pom 配置文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>org.example</groupId>
    <artifactId>mybatis-plus-demo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.3.1</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.5.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.3</version>
        </dependency>
        
        <!--驅(qū)動-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.26</version>
        </dependency>
        
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.6</version>
        </dependency>
        
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.20</version>
            <scope>provided</scope>
        </dependency>
        
        <!--通用工具猩谊,json轉(zhuǎn)換等-->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.7.7</version>
        </dependency>


    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

配置文件

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/user?useUnicode=true&characterEncoding=utf-8&useSSL=false&allowMultiQueries=true
    username: root
    password: 123456

mybatis-plus:
# 對枚舉類的處理,枚舉如果沒有實現(xiàn)指定的接口 IEnum<Integer>的話祭刚,需要專門的進行配置掃描包
  typeEnumsPackage: com.org.example.domain.type

logging:
  level:
    com.org.example.dao.mapper: debug

生成的的實體類,需要手動的將需要進行轉(zhuǎn)換的屬性進行屬性的變更以及typeHandler的選取牌捷,這個類很重要,之后需要單獨維護袁梗,整個轉(zhuǎn)換器再這個上邊進行使用

package com.org.example.domain.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import java.io.Serializable;
import java.time.Instant;
import java.util.List;

import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler;
import com.org.example.dao.typehandler.InstantMsLongTypeHandler;
import com.org.example.dao.typehandler.LiveAttrListTypeHandler;
import com.org.example.dao.typehandler.LiveChannelListTypeHandler;
import com.org.example.domain.type.PushStreamType;
import com.org.example.domain.type.StatusType;
import lombok.Data;
import lombok.EqualsAndHashCode;

@Data
@TableName(autoResultMap = true)
@EqualsAndHashCode(callSuper = false)
public class PlConfigProject implements Serializable {



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

    @TableField("project_id")
    private String projectId;

    @TableField(value = "live_channel_info", typeHandler = LiveChannelListTypeHandler.class)
    private List<LiveChannelInfo> liveChannelInfo;

    @TableField(value = "cloud_store_info", typeHandler = JacksonTypeHandler.class)
    private CloudStoreInfo cloudStoreInfo;

    /**
     * 直播初始化屬性包括 視頻屬性宜鸯,音頻屬性,錄屏屬性等
     */
    @TableField(value = "live_attr", typeHandler = LiveAttrListTypeHandler.class)
    private List<LiveAttr> liveAttr;

    /**
     * 狀態(tài)屬性 1 未激活 2激活  3禁用 4刪除
     */
    private StatusType status;

    @TableField("push_stream_type")
    private PushStreamType pushStreamType;

    @TableField(value = "create_time", typeHandler = InstantMsLongTypeHandler.class)
    private Instant createTime;

    @TableField(value = "update_time", typeHandler = InstantMsLongTypeHandler.class)
    private Instant updateTime;

    private Integer version;


}

枚舉類的創(chuàng)建

實現(xiàn)mybatis-plus的接口遮怜,則不需要再配置文件中配置相應(yīng)的路徑淋袖,但是需要重寫getValue方法
package com.org.example.domain.type;

import com.baomidou.mybatisplus.annotation.EnumValue;
import com.baomidou.mybatisplus.annotation.IEnum;


public enum StatusType implements IEnum<Integer> {
    //狀態(tài)屬性 1 未激活 2激活  3已使用 4刪除
    STATUS_INACTIVATED(1, "未激活"),
    STATUS_ACTIVATED(2, "激活"),
    STATUS_USED(3, "已使用"),
    STATUS_DELETED(4, "刪除"),
    ;

    @EnumValue
    private int code;

    private String description;

    StatusType(int code, String description) {
        this.code = code;
        this.description = description;
    }

    @Override
    public Integer getValue() {
        return this.code;
    }

    public String getCodeString() {
        return name();
    }

    public String getDescription() {
        return description;
    }


}

如果自定義枚舉的話,需要再配置文件中配置文件的路徑锯梁,進行掃描mybatis-plus.

typeEnumsPackage=com.org.example.domain.type

public enum PushStreamType implements Enumerable {

    RTMP(0, "rtmp推流"),
    RTC(1, "rtc推流"),
    RTMP_RTC(2, "rtc & rtmp 推流"),
    ;

    @EnumValue
    private int code;

    private String description;

    PushStreamType(int code, String description) {
        this.code = code;
        this.description = description;
    }

    @Override
    public int getCode() {
        return code;
    }

    @Override
    public String getCodeString() {
        return name();
    }

    @Override
    public String getDescription() {
        return description;
    }
}


public interface Enumerable {

    int getCode();

    String getCodeString();

    String getDescription();
}

使用的typeHandler定義

// instant 2 bigint的轉(zhuǎn)換
package com.org.example.dao.typehandler;


import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.Instant;

public class InstantMsLongTypeHandler extends BaseTypeHandler<Instant> {
    public InstantMsLongTypeHandler() {
    }

    public void setNonNullParameter(PreparedStatement ps, int i, Instant parameter, JdbcType jdbcType) throws SQLException {
        ps.setLong(i, parameter.toEpochMilli());
    }

    public Instant getNullableResult(ResultSet rs, String columnName) throws SQLException {
        long value = rs.getLong(columnName);
        if (rs.wasNull()) {
            return null;
        } else {
            return value > 0L ? Instant.ofEpochMilli(value) : null;
        }
    }

    public Instant getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        long value = rs.getLong(columnIndex);
        if (rs.wasNull()) {
            return null;
        } else {
            return value > 0L ? Instant.ofEpochMilli(value) : null;
        }
    }

    public Instant getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        long value = cs.getLong(columnIndex);
        if (cs.wasNull()) {
            return null;
        } else {
            return value > 0L ? Instant.ofEpochMilli(value) : null;
        }
    }
}


// instant 2 timestamp 的轉(zhuǎn)換器
public class InstantTimestampTypeHandler extends BaseTypeHandler<Instant> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Instant parameter, JdbcType jdbcType) throws SQLException {
        ps.setTimestamp(i, new Timestamp(parameter.toEpochMilli()));
    }

    @Override
    public Instant getNullableResult(ResultSet rs, String columnName)
            throws SQLException {
        Timestamp value = rs.getTimestamp(columnName);
        if (rs.wasNull()) {
            return null;
        } else {
            return Instant.ofEpochMilli(value.getTime());
        }
    }

    @Override
    public Instant getNullableResult(ResultSet rs, int columnIndex)
            throws SQLException {
        Timestamp value = rs.getTimestamp(columnIndex);
        if (rs.wasNull()) {
            return null;
        } else {
            return Instant.ofEpochMilli(value.getTime());
        }
    }

    @Override
    public Instant getNullableResult(CallableStatement cs, int columnIndex)
            throws SQLException {
        Timestamp value = cs.getTimestamp(columnIndex);
        if (cs.wasNull()) {
            return null;
        } else {
            return Instant.ofEpochMilli(value.getTime());
        }
    }
}

// 其他復(fù)雜類型轉(zhuǎn)換器

public class LiveAttrListTypeHandler extends BaseTypeHandler<List<LiveAttr>> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i,
                                    List<LiveAttr> parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, toValue(parameter));
    }

    @Override
    public List<LiveAttr> getNullableResult(ResultSet rs, String columnName)
            throws SQLException {
        String value = rs.getString(columnName);
        if (rs.wasNull()) {
            return null;
        } else {
            return convert(value);
        }
    }

    @Override
    public List<LiveAttr> getNullableResult(ResultSet rs, int columnIndex)
            throws SQLException {
        String value = rs.getString(columnIndex);
        if (rs.wasNull()) {
            return null;
        } else {
            return convert(value);
        }
    }

    @Override
    public List<LiveAttr> getNullableResult(CallableStatement cs, int columnIndex)
            throws SQLException {
        String value = cs.getString(columnIndex);
        if (cs.wasNull()) {
            return null;
        } else {
            return convert(value);
        }
    }

    private List<LiveAttr> convert(String value) {
        return JSONUtil.toBean(value, new TypeReference<List<LiveAttr>>() {
        }, true);
    }

    private String toValue(List<LiveAttr> parameter) {

        return JSONUtil.toJsonStr(parameter);
    }
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末即碗,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子陌凳,更是在濱河造成了極大的恐慌剥懒,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,657評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件合敦,死亡現(xiàn)場離奇詭異初橘,居然都是意外死亡,警方通過查閱死者的電腦和手機充岛,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,889評論 3 394
  • 文/潘曉璐 我一進店門保檐,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人崔梗,你說我怎么就攤上這事夜只。” “怎么了蒜魄?”我有些...
    開封第一講書人閱讀 164,057評論 0 354
  • 文/不壞的土叔 我叫張陵扔亥,是天一觀的道長场躯。 經(jīng)常有香客問我,道長旅挤,這世上最難降的妖魔是什么踢关? 我笑而不...
    開封第一講書人閱讀 58,509評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮谦铃,結(jié)果婚禮上耘成,老公的妹妹穿的比我還像新娘。我一直安慰自己驹闰,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,562評論 6 392
  • 文/花漫 我一把揭開白布撒会。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪血久。 梳的紋絲不亂的頭發(fā)上箱蟆,一...
    開封第一講書人閱讀 51,443評論 1 302
  • 那天,我揣著相機與錄音怔檩,去河邊找鬼褪秀。 笑死,一個胖子當(dāng)著我的面吹牛薛训,可吹牛的內(nèi)容都是我干的媒吗。 我是一名探鬼主播,決...
    沈念sama閱讀 40,251評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼乙埃,長吁一口氣:“原來是場噩夢啊……” “哼闸英!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起介袜,我...
    開封第一講書人閱讀 39,129評論 0 276
  • 序言:老撾萬榮一對情侶失蹤甫何,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后遇伞,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體辙喂,經(jīng)...
    沈念sama閱讀 45,561評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,779評論 3 335
  • 正文 我和宋清朗相戀三年鸠珠,在試婚紗的時候發(fā)現(xiàn)自己被綠了巍耗。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,902評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡跳芳,死狀恐怖芍锦,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情飞盆,我是刑警寧澤娄琉,帶...
    沈念sama閱讀 35,621評論 5 345
  • 正文 年R本政府宣布次乓,位于F島的核電站,受9級特大地震影響孽水,放射性物質(zhì)發(fā)生泄漏票腰。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,220評論 3 328
  • 文/蒙蒙 一女气、第九天 我趴在偏房一處隱蔽的房頂上張望杏慰。 院中可真熱鬧,春花似錦炼鞠、人聲如沸缘滥。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,838評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽朝扼。三九已至,卻和暖如春霎肯,著一層夾襖步出監(jiān)牢的瞬間擎颖,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,971評論 1 269
  • 我被黑心中介騙來泰國打工观游, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留搂捧,地道東北人。 一個月前我還...
    沈念sama閱讀 48,025評論 2 370
  • 正文 我出身青樓懂缕,卻偏偏與公主長得像允跑,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子提佣,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,843評論 2 354