Springboot integrates mybatis to automatically generate entity classes and mapper

Time:2021-10-16

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

<properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <!--  Mybatis automatically generates Dao layer configuration according to entity classes -- >
        <!--  MyBatis Generator  -->
        <targetJavaProject>${basedir}/src/main/java</targetJavaProject>
        <!--   Java interface -- >
        <targetMapperPackage>com.jiafly.falsework.dao</targetMapperPackage>
        <!--  Entity class -- >
        <targetModelPackage>com.jiafly.falsework.entity</targetModelPackage>
        <!--   XML generation path -- >
        <targetResourcesProject>${basedir}/src/main/resources</targetResourcesProject>
        <targetXMLPackage>mapper</targetXMLPackage>
    </properties>

        <!--  Mybatis general mapper configuration -- >
        <!--  Spring boot mybatis dependency -- >
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>RELEASE</version>
        </dependency>
        <!--  MySQL connection driver dependency -- >
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.39</version>
            <scope>runtime</scope>
        </dependency>
        <!-- mapper -->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
            <version>1.2.3</version>
        </dependency>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <!-- mybatis-generator-maven-plugin -->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.2</version>
                <configuration>
                    <configurationFile>${basedir}/src/main/resources/generatorConfig.xml</configurationFile>
                    <overwrite>false</overwrite>
                    <verbose>true</verbose>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>5.1.39</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>

3. Configure in application.yml

spring:
  #Database related configuration
  datasource:
    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
mybatis:
  mapperLocations: classpath:mapper/*.xml
  typeAliasesPackage: com.jiafly.libra.entity
#General mapper configuration automatically generates Dao layer code
mapper:
  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"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
    <properties resource="application.yml"/>

    <context id="Mysql" targetRuntime="MyBatis3" defaultModelType="flat">
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/jiafly"
                        userId="root"
                        password="root">
        </jdbcConnection>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
        <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"/>
        </javaModelGenerator>

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

        <javaClientGenerator targetPackage="${targetMapperPackage}" targetProject="${targetJavaProject}" type="XMLMAPPER" >
            <property name="enableSubPackages" value="false" />
        </javaClientGenerator>
        <!--  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>
    </context>
</generatorConfiguration>

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 {
    @Id
    @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;

}

Interface

package com.jiafly.libra.mapper;

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

public interface UserInfoMapper extends Mapper<UserInfo> {

}

xml

<?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" >


</mapper>

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 […]