spring boot integrates MyBatis Generator to automatically generate dynamic sql code

Catalog

1. Background

2. Practice

3. Summary

1. Background

         When you recently used mybatis, you saw an article that used yml configuration to simplify the xml configuration MyBatis Generator uses by default, and you wanted to use the MyBatis Generator provided by someone to automatically generate some bean s, dynamic mapper files.

Project consolidation address: https://github.com/xujiankang6/study/tree/main/spring-boot-researchhttps://github.com/xujiankang6/study/tree/main/spring-boot-research

2. Practice

1. Add this plugin to maven

(1) Configuration yml file path with the configurationFile property MyBatis Generator.

            <plugin>
                <groupId>io.github.javthon</groupId>
                <artifactId>mybatis-generator-yml-maven-plugin</artifactId>
                <version>0.0.1</version>
                <configuration>
                    <configurationFile>src/main/resources/generator/generatorConfig.yml</configurationFile>
                </configuration>
            </plugin>

2. GeneorConfig.yml configuration file

(1) Configuration as follows

mybatisGenerator:
  datasource:
    type: mysql
    address: localhost:3306
    db: test?serverTimezone=GMT
    driver-class-name: com.mysql.jdbc.Driver
    username: root
    password: 123456

  targetPackage:
    model: com.example.demo.model
    mapper: com.example.demo.mapper
    javaXmlFilesSamePackage: true

  targetRuntime: MyBatis3DynamicSql
  mapperSuffixName: mapper
  java8: false
  disableExample: true

  plugins:
    comment: true
    lombok: false
    swagger: false
    mapperAnnotation: false
    serializable: false

  tables:
    - user

  (2) Description of main attributes

attributetypeDefault valueIs it necessarydescribe
datasourceMapyesConnection information for the database, see "Data Source Configuration" below
targetPackageMapyesPackage path to generate code, see targetPackage configuration below
targetRuntimeStringMyBatis3yesmybatis generator production code format I use MyBatis 3DynamicSql
mapperSuffixNameStringmappernoThe suffix name of the mapper class or XML file. If this property is set to dao and the table name is user, it will generate UserDao.java and UserDao.xml. If targetRuntime is set to MyBatis3DynamicSql, this property will not work
java8BooleanfalsenoIf true, the generated model date field will use Java8's LocalDateTime or LocalDate, otherwise use Date
disableExampleBooleantruenoThis property only works if the targetRuntime is MyBatis3, and mapper does not generate "by example" code when true
pluginsMapnoConfigure whether to turn on annotations, lombok, swagger, mapperAnnotation, serializable and other plug-ins
tablesListyesMultiple table names, configured as shown in the following example

(3) More configurations to see the plug-in git repository mybatis-generator-yml-maven-plugin/Readme-CN.md at master · javthon/mybatis-generator-yml-maven-plugin · GitHub

(4) Currently only sqlserver, mysql, oracle are supported.

(5) Note that the above db configuration requires this attribute to be appended to the database name? serverTimezone=GMT, otherwise the following error will be reported:

[ERROR] The server time zone value '�й���׼ʱ��' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the 'serverTimezone' configuration property) to use a more specifc time zone value if you want to utilize time zone support.

  3. Execute the plug-in through idea

(1) Multiple executions can be performed, each execution overwriting the last generated code.

  4. View results

(1) The automatically generated bean files are as follows:

public class User {
    /**
     */
    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    private Integer uid;

    /**
     */
    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    private String uname;

    /**
     */
    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    private String upwd;

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    public Integer getUid() {
        return uid;
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    public void setUid(Integer uid) {
        this.uid = uid;
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    public String getUname() {
        return uname;
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    public void setUname(String uname) {
        this.uname = uname;
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    public String getUpwd() {
        return upwd;
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    public void setUpwd(String upwd) {
        this.upwd = upwd;
    }
}

(2) The automatically generated mapper file is as follows:

@Mapper
public interface UserMapper {
    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    BasicColumn[] selectList = BasicColumn.columnList(uid, uname, upwd);

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    @SelectProvider(type=SqlProviderAdapter.class, method="select")
    long count(SelectStatementProvider selectStatement);

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    @DeleteProvider(type=SqlProviderAdapter.class, method="delete")
    int delete(DeleteStatementProvider deleteStatement);

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    @InsertProvider(type=SqlProviderAdapter.class, method="insert")
    int insert(InsertStatementProvider<User> insertStatement);

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    @InsertProvider(type=SqlProviderAdapter.class, method="insertMultiple")
    int insertMultiple(MultiRowInsertStatementProvider<User> multipleInsertStatement);

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    @SelectProvider(type=SqlProviderAdapter.class, method="select")
    @Results(id="UserResult", value = {
        @Result(column="uid", property="uid", jdbcType=JdbcType.INTEGER, id=true),
        @Result(column="uname", property="uname", jdbcType=JdbcType.VARCHAR),
        @Result(column="upwd", property="upwd", jdbcType=JdbcType.VARCHAR)
    })
    Optional<User> selectOne(SelectStatementProvider selectStatement);

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    @SelectProvider(type=SqlProviderAdapter.class, method="select")
    @Results(id="UserResult", value = {
        @Result(column="uid", property="uid", jdbcType=JdbcType.INTEGER, id=true),
        @Result(column="uname", property="uname", jdbcType=JdbcType.VARCHAR),
        @Result(column="upwd", property="upwd", jdbcType=JdbcType.VARCHAR)
    })
    List<User> selectMany(SelectStatementProvider selectStatement);

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    @UpdateProvider(type=SqlProviderAdapter.class, method="update")
    int update(UpdateStatementProvider updateStatement);

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    default long count(CountDSLCompleter completer) {
        return MyBatis3Utils.countFrom(this::count, user, completer);
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    default int delete(DeleteDSLCompleter completer) {
        return MyBatis3Utils.deleteFrom(this::delete, user, completer);
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    default int deleteByPrimaryKey(Integer uid_) {
        return delete(c -> 
            c.where(uid, isEqualTo(uid_))
        );
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    default int insert(User record) {
        return MyBatis3Utils.insert(this::insert, record, user, c ->
            c.map(uid).toProperty("uid")
            .map(uname).toProperty("uname")
            .map(upwd).toProperty("upwd")
        );
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    default int insertMultiple(Collection<User> records) {
        return MyBatis3Utils.insertMultiple(this::insertMultiple, records, user, c ->
            c.map(uid).toProperty("uid")
            .map(uname).toProperty("uname")
            .map(upwd).toProperty("upwd")
        );
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    default int insertSelective(User record) {
        return MyBatis3Utils.insert(this::insert, record, user, c ->
            c.map(uid).toPropertyWhenPresent("uid", record::getUid)
            .map(uname).toPropertyWhenPresent("uname", record::getUname)
            .map(upwd).toPropertyWhenPresent("upwd", record::getUpwd)
        );
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    default Optional<User> selectOne(SelectDSLCompleter completer) {
        return MyBatis3Utils.selectOne(this::selectOne, selectList, user, completer);
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    default List<User> select(SelectDSLCompleter completer) {
        return MyBatis3Utils.selectList(this::selectMany, selectList, user, completer);
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    default List<User> selectDistinct(SelectDSLCompleter completer) {
        return MyBatis3Utils.selectDistinct(this::selectMany, selectList, user, completer);
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    default Optional<User> selectByPrimaryKey(Integer uid_) {
        return selectOne(c ->
            c.where(uid, isEqualTo(uid_))
        );
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    default int update(UpdateDSLCompleter completer) {
        return MyBatis3Utils.update(this::update, user, completer);
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    static UpdateDSL<UpdateModel> updateAllColumns(User record, UpdateDSL<UpdateModel> dsl) {
        return dsl.set(uid).equalTo(record::getUid)
                .set(uname).equalTo(record::getUname)
                .set(upwd).equalTo(record::getUpwd);
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    static UpdateDSL<UpdateModel> updateSelectiveColumns(User record, UpdateDSL<UpdateModel> dsl) {
        return dsl.set(uid).equalToWhenPresent(record::getUid)
                .set(uname).equalToWhenPresent(record::getUname)
                .set(upwd).equalToWhenPresent(record::getUpwd);
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    default int updateByPrimaryKey(User record) {
        return update(c ->
            c.set(uname).equalTo(record::getUname)
            .set(upwd).equalTo(record::getUpwd)
            .where(uid, isEqualTo(record::getUid))
        );
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    default int updateByPrimaryKeySelective(User record) {
        return update(c ->
            c.set(uname).equalToWhenPresent(record::getUname)
            .set(upwd).equalToWhenPresent(record::getUpwd)
            .where(uid, isEqualTo(record::getUid))
        );
    }

(3) The automatically generated mapper support classes are as follows:

public final class UserDynamicSqlSupport {
    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    public static final User user = new User();

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    public static final SqlColumn<Integer> uid = user.uid;

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    public static final SqlColumn<String> uname = user.uname;

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    public static final SqlColumn<String> upwd = user.upwd;

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    public static final class User extends SqlTable {
        public final SqlColumn<Integer> uid = column("uid", JDBCType.INTEGER);

        public final SqlColumn<String> uname = column("uname", JDBCType.VARCHAR);

        public final SqlColumn<String> upwd = column("upwd", JDBCType.VARCHAR);

        public User() {
            super("user");
        }
    }
}

5. The mybatis-related maven dependencies used in project integration are as follows

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot</artifactId>
            <version>2.0.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.mybatis.dynamic-sql/mybatis-dynamic-sql -->
        <dependency>
            <groupId>org.mybatis.dynamic-sql</groupId>
            <artifactId>mybatis-dynamic-sql</artifactId>
            <version>1.3.0</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.35</version>
        </dependency>

3. Summary

         This is to achieve spring boot to integrate all the contents of MyBatis Generator to automatically generate dynamic sql code. I hope it can help you, you can download it from git, refer to it, feel good, welcome to WeChat Search to focus on java basic notes, after which we will keep updating related knowledge, and everyone will progress together.

https://github.com/xujiankang6/study/tree/main/spring-boot-researchhttps://github.com/xujiankang6/study/tree/main/spring-boot-research

Keywords: Maven Mybatis Spring Boot generator

Added by alexander.s on Sun, 21 Nov 2021 19:02:16 +0200