SpringBoot集成Mybatis 自動生成實體類和Mapper

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也一併刪除,以後增長字段就不須要再去維護
  • 優化後的文件以下;

實體類java

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;

}

接口mysql

package com.jiafly.libra.mapper;

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

public interface UserInfoMapper extends Mapper<UserInfo> {

}

xmlspring

<?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語句便可。
相關文章
相關標籤/搜索