Springboot integrates mybatis to automatically generate entity classes and mapper


Springboot integrates mybatis to automatically generate entity classes and mapper

1. Create an empty springboot project using idea

2. Introduce the following configuration in pom.xml

        <!--  Mybatis automatically generates Dao layer configuration according to entity classes -- >
        <!--  MyBatis Generator  -->
        <!--   Java interface -- >
        <!--  Entity class -- >
        <!--   XML generation path -- >

        <!--  Mybatis general mapper configuration -- >
        <!--  Spring boot mybatis dependency -- >
        <!--  MySQL connection driver dependency -- >
        <!-- mapper -->

            <!-- mybatis-generator-maven-plugin -->

3. Configure in application.yml

  #Database related configuration
    url: jdbc:mysql://localhost:3306/jiafly?useUnicode=true&characterEncoding=UTF-8&useSSL=false&useTimezone=true&serverTimezone=Asia/Shanghai&allowMultiQueries=true
    username: root
    password: root
    driver-class-name: com.mysql.jdbc.Driver
    initialSize: 1
    minIdle: 1
    maxActive: 5
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 180000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false

#Mybatties configuration
  mapperLocations: classpath:mapper/*.xml
  typeAliasesPackage: com.jiafly.libra.entity
#General mapper configuration automatically generates Dao layer code
  plugin: tk.mybatis.mapper.generator.MapperPlugin
  Mapper: tk.mybatis.mapper.common.Mapper
  not-empty: false
  identity: MYSQL

4. Create generatorconfig.xml file in Src / main / Resources folder

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"

    <properties resource="application.yml"/>

    <context id="Mysql" targetRuntime="MyBatis3" defaultModelType="flat">
            <property name="suppressDate" value="true"/>
            <property name="suppressAllComments" value="true"/>
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
            <property name="forceBigDecimals" value="false"/>
        <javaModelGenerator targetPackage="${targetModelPackage}" targetProject="${targetJavaProject}">
            <!--  Allow sub packages, i.e. targetpackage. Schemaname. Tablename -- >
            <property name="enableSubPackages" value="false"/>
            <!--  Add constructor to model -- >
            <property name="constructorBased" value="true"/>
            <!--  Whether to trim the data of char like columns -- >
            <property name="trimStrings" value="true"/>
            <!--  Whether the established model object cannot be changed, that is, the generated model object will not have a setter method, but only a construction method -- >
            <property name="immutable" value="false"/>

        <sqlMapGenerator targetPackage="${targetXMLPackage}"  targetProject="${targetResourcesProject}">
            <property name="enableSubPackages" value="false"/>

        <javaClientGenerator targetPackage="${targetMapperPackage}" targetProject="${targetJavaProject}" type="XMLMAPPER" >
            <property name="enableSubPackages" value="false" />
        <!--  Tablename is the table name of the database, and domainobjectname is the name of the generated entity class -- >
        <table tableName="user_info" domainObjectName="UserInfo" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>

5. Execute the mybatis generator Maven plugin

  • After execution, the entity class will be generated in com.jiafly.library.entity, the Dao layer interface will be generated in com.jiafly.library.mapper, and the XML file will be generated in resources.mapper.

6. Optimization

  • When we add fields to the database, we need to add fields to the corresponding entity class, and we also need to add fields to XML for maintenance, which will consume a lot of time
  • We can let the interface inherit mapper < T > and delete all methods in the interface, because they have been implemented in mapper. The SQL in the XML is also deleted, and the added fields do not need to be maintained
  • The optimized documents are as follows;

Entity class

package com.jiafly.libra.entity;

import java.util.Date;

public class UserInfo {
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String userId;

    private String mobile;

    private String email;

    private String openId;

    private String unionId;

    private String userName;

    private String nickName;

    private Byte gender;

    private Integer age;

    private String city;

    private String province;

    private String country;

    private String password;

    private Byte vip;

    private Byte delFlag;

    private Date createTime;

    private Date updateTime;



package com.jiafly.libra.mapper;

import com.jiafly.libra.entity.UserInfo;
import tk.mybatis.mapper.common.Mapper;

public interface UserInfoMapper extends Mapper<UserInfo> {



<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.jiafly.libra.mapper.UserInfoMapper" >


7. Inherit the pit encountered by mapper < T >

  • The @ ID annotation needs to be added to the primary key of the entity. Otherwise, the general mapper cannot recognize the primary key. When using the mapper method to update and search, all conditions will be brought, resulting in no data being found.
  • There will be no error when you encounter this problem. Just pay attention to the printed SQL statement.

Recommended Today

Swift advanced (XV) extension

The extension in swift is somewhat similar to the category in OC Extension can beenumeration、structural morphology、class、agreementAdd new features□ you can add methods, calculation attributes, subscripts, (convenient) initializers, nested types, protocols, etc What extensions can’t do:□ original functions cannot be overwritten□ you cannot add storage attributes or add attribute observers to existing attributes□ cannot add parent […]