SpringBoot集成Mybatis 自动生成实体类和Mapper

1.使用IDEA创建一个空的SpringBoot项目

2.在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 根据实体类自动生成dao层配置-->
        <!--  MyBatis Generator  -->
        <targetJavaProject>${basedir}/src/main/java</targetJavaProject>
        <!--  Java接口  -->
        <targetMapperPackage>com.jiafly.falsework.dao</targetMapperPackage>
        <!-- 实体类 -->
        <targetModelPackage>com.jiafly.falsework.entity</targetModelPackage>
        <!--  XML生成路径  -->
        <targetResourcesProject>${basedir}/src/main/resources</targetResourcesProject>
        <targetXMLPackage>mapper</targetXMLPackage>
    </properties>

        <!-- mybatis 通用mapper配置 -->
        <!-- Spring Boot Mybatis 依赖 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>RELEASE</version>
        </dependency>
        <!-- MySQL 连接驱动依赖 -->
        <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. 在application.yml中配置

spring:
  # 数据库相关配置
  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

# mybaties 配置
mybatis:
  mapperLocations: classpath:mapper/*.xml
  typeAliasesPackage: com.jiafly.libra.entity
# 通用mapper 配置 自动生成dao层代码
mapper:
  plugin: tk.mybatis.mapper.generator.MapperPlugin
  Mapper: tk.mybatis.mapper.common.Mapper
  not-empty: false
  identity: MYSQL

4. 在src/main/resources文件夹下创建generatorConfig.xml文件

<?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}">
            <!-- 是否允许子包,即targetPackage.schemaName.tableName -->
            <property name="enableSubPackages" value="false"/>
            <!-- 是否对model添加 构造函数 -->
            <property name="constructorBased" value="true"/>
            <!-- 是否对类CHAR类型的列的数据进行trim操作 -->
            <property name="trimStrings" value="true"/>
            <!-- 建立的Model对象是否 不可改变  即生成的Model对象不会有 setter方法,只有构造方法 -->
            <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是数据库的表名,domainObjectName是生成的实体类名称 -->
        <table tableName="user_info" domainObjectName="UserInfo" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
    </context>
</generatorConfiguration>

5. 执行mybatis-generator-maven-plugin插件

  • 执行完毕后会在 com.jiafly.libra.entity中生成实体类,com.jiafly.libra.mapper中生成dao层接口 resources.mapper中生成xml文件。

6. 优化

  • 当我们在数据库中增加字段时,需要在对应的实体类中增加字段,xml中也需要去增加字段,去维护,会消耗大量的时间
  • 我们可以让接口去继承 Mapper<T> ,删除接口中的所有方法,因为Mapper中都已经实现了。对于的xml中的sql也一并删除,之后增加字段就不需要再去维护
  • 优化后的文件如下;

实体类

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;

}

接口

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.继承Mapper<T>遇到的坑

  • 需要在实体的主键上增加@Id注解,否则通用mapper无法识别主键,在是使用mapper的方法做更新查找等操作的时候会带上所有的条件,造成找不到数据。
  • 遇到这里问题不会报错,只要注意打印出来的sql语句即可。

南桥听雨声
82 声望4 粉丝