1. 程式人生 > >SpringBoot使用Mybatis-Generator

SpringBoot使用Mybatis-Generator

dex packages art tid 自動生成文件 try cee pro rds

本文介紹如何將Maven和Mybatis-Generator配合使用。

技術分享圖片

簡介

Mybatis-Generator是Mybatis提供的一個便捷型插件,自動可以為項目生產對應的實體類,Mapper,dao層。

官網文檔:http://www.mybatis.org/generator/index.html

入門案例

本文使用SpringBoot結合Mybatis-Generator插件使用,數據庫Mysql。

新建項目

新建一個SpringBoot項目。

依賴文件

在項目pom文件中,引入Mybatis-Generator插件,並且引入Mybatis和Mysql依賴。完整pom代碼如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.dalaoyang</groupId>
    <artifactId>springboot_generator</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>springboot_generator</name>
    <description>springboot_generator</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.15.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.2</version>
                <executions>
                    <execution>
                        <id>mybatis-generator</id>
                        <phase>deploy</phase>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <!-- Mybatis-Generator 工具配置文件的位置 -->
                    <configurationFile>src/main/resources/mybatis-generator/generatorConfig.xml</configurationFile>
                    <verbose>true</verbose>
                    <overwrite>true</overwrite>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>5.1.46</version>
                    </dependency>
                    <dependency>
                        <groupId>org.mybatis.generator</groupId>
                        <artifactId>mybatis-generator-core</artifactId>
                        <version>1.3.2</version>
                    </dependency>
                </dependencies>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <classifier>exec</classifier>
                </configuration>
            </plugin>
        </plugins>
    </build>


</project>

配置Mybatis-Generator配置

在pom文件中配置的Mybatis-Generator 工具配置文件的位置新建一個generatorConfig.xml,(本文案例配置的位置是src/main/resources/mybatis-generator/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>
    <!--執行generator插件生成文件的命令: call mvn mybatis-generator:generate -e -->
    <!-- 引入配置文件 -->
    <properties resource="application.properties"/>
    <!--classPathEntry:數據庫的JDBC驅動,換成你自己的驅動位置 可選 -->
    <!--<classPathEntry location="D:generator_mybatismysql-connector-java-5.1.24-bin.jar" /> -->

    <!-- 一個數據庫一個context -->
    <!--defaultModelType="flat" 大數據字段,不分表 -->
    <context id="MysqlTables" targetRuntime="MyBatis3Simple" defaultModelType="flat">
        <!-- 自動識別數據庫關鍵字,默認false,如果設置為true,根據SqlReservedWords中定義的關鍵字列表;
        一般保留默認值,遇到數據庫關鍵字(Java關鍵字),使用columnOverride覆蓋 -->
        <property name="autoDelimitKeywords" value="true" />
        <!-- 生成的Java文件的編碼 -->
        <property name="javaFileEncoding" value="utf-8" />
        <!-- beginningDelimiter和endingDelimiter:指明數據庫的用於標記數據庫對象名的符號,比如ORACLE就是雙引號,MYSQL默認是`反引號; -->
        <property name="beginningDelimiter" value="`" />
        <property name="endingDelimiter" value="`" />

        <!-- 格式化java代碼 -->
        <property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"/>
        <!-- 格式化XML代碼 -->
        <property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter"/>
        <plugin type="org.mybatis.generator.plugins.SerializablePlugin" />

        <plugin type="org.mybatis.generator.plugins.ToStringPlugin" />

        <!-- 註釋 -->
        <commentGenerator >
            <property name="suppressAllComments" value="false"/><!-- 是否取消註釋 -->
            <property name="suppressDate" value="true" /> <!-- 是否生成註釋代時間戳-->
        </commentGenerator>

        <!-- jdbc連接 -->
        <jdbcConnection driverClass="${spring.datasource.driver-class-name}" connectionURL="${spring.datasource.url}" userId="${spring.datasource.username}" password="${spring.datasource.password}" />
        <!-- 類型轉換 -->
        <javaTypeResolver>
            <!-- 是否使用bigDecimal, false可自動轉化以下類型(Long, Integer, Short, etc.) -->
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>

        <!-- 生成實體類地址 -->
        <javaModelGenerator targetPackage="com.dalaoyang.entity" targetProject="${mybatis.project}" >
            <property name="enableSubPackages" value="false"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <!-- 生成mapxml文件 -->
        <sqlMapGenerator targetPackage="mapper" targetProject="${mybatis.resources}" >
            <property name="enableSubPackages" value="false" />
        </sqlMapGenerator>
        <!-- 生成mapxml對應client,也就是接口dao -->
        <javaClientGenerator targetPackage="com.dalaoyang.dao" targetProject="${mybatis.project}" type="XMLMAPPER" >
            <property name="enableSubPackages" value="false" />
        </javaClientGenerator>
        <!-- table可以有多個,每個數據庫中的表都可以寫一個table,tableName表示要匹配的數據庫表,也可以在tableName屬性中通過使用%通配符來匹配所有數據庫表,只有匹配的表才會自動生成文件 -->
        <table tableName="user" enableCountByExample="true" enableUpdateByExample="true" enableDeleteByExample="true" enableSelectByExample="true" selectByExampleQueryId="true">
            <property name="useActualColumnNames" value="false" />
            <!-- 數據庫表主鍵 -->
            <generatedKey column="id" sqlStatement="Mysql" identity="true" />
        </table>
        <table tableName="book" enableCountByExample="true" enableUpdateByExample="true" enableDeleteByExample="true" enableSelectByExample="true" selectByExampleQueryId="true">
            <property name="useActualColumnNames" value="false" />
            <!-- 數據庫表主鍵 -->
            <generatedKey column="id" sqlStatement="Mysql" identity="true" />
        </table>
    </context>
</generatorConfiguration>

配置application.properties

配置項目的application.properties,其中數據庫信息,Mapper地址之前都有過介紹,具體SpringBoot-Mybatis配置可以參考:
《SpringBoot+Mybatis+MySql學習》

本文配置如下:

## mapper xml 文件地址
mybatis.mapper-locations=classpath*:mapper/*Mapper.xml

##數據庫url
spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=false
##數據庫用戶名
spring.datasource.username=root
##數據庫密碼
spring.datasource.password=123456
##數據庫驅動
spring.datasource.driver-class-name=com.mysql.jdbc.Driver


#Mybatis Generator configuration
#dao類和實體類的位置
mybatis.project =src/main/java
#mapper文件的位置
mybatis.resources=src/main/resources

到這裏其實配置就完成了,可以體驗Mybatis-Generator插件的優點了,在右側Maven處點擊如圖所示位置,如圖:

技術分享圖片

點擊完成後,可以看到Mapper,dao,實體類都已經創建好了,如圖:

技術分享圖片

創建完成會給我生成幾個默認的建當方法,如UserMapper代碼如下:

package com.dalaoyang.dao;

import com.dalaoyang.entity.User;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

public interface UserMapper {
    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table user
     *
     * @mbggenerated
     */
    int deleteByPrimaryKey(Long id);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table user
     *
     * @mbggenerated
     */
    int insert(User record);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table user
     *
     * @mbggenerated
     */
    User selectByPrimaryKey(Long id);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table user
     *
     * @mbggenerated
     */
    List<User> selectAll();

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table user
     *
     * @mbggenerated
     */
    int updateByPrimaryKey(User record);
}

UserMapper.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.dalaoyang.dao.UserMapper" >
  <resultMap id="BaseResultMap" type="com.dalaoyang.entity.User" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    <id column="id" property="id" jdbcType="BIGINT" />
    <result column="user_name" property="userName" jdbcType="VARCHAR" />
    <result column="user_password" property="userPassword" jdbcType="VARCHAR" />
  </resultMap>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Long" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    delete from user
    where id = #{id,jdbcType=BIGINT}
  </delete>
  <insert id="insert" parameterType="com.dalaoyang.entity.User" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    <selectKey resultType="java.lang.Long" keyProperty="id" order="AFTER" >
      SELECT LAST_INSERT_ID()
    </selectKey>
    insert into user (user_name, user_password)
    values (#{userName,jdbcType=VARCHAR}, #{userPassword,jdbcType=VARCHAR})
  </insert>
  <update id="updateByPrimaryKey" parameterType="com.dalaoyang.entity.User" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    update user
    set user_name = #{userName,jdbcType=VARCHAR},
      user_password = #{userPassword,jdbcType=VARCHAR}
    where id = #{id,jdbcType=BIGINT}
  </update>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    select id, user_name, user_password
    from user
    where id = #{id,jdbcType=BIGINT}
  </select>
  <select id="selectAll" resultMap="BaseResultMap" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    select id, user_name, user_password
    from user
  </select>
</mapper>

測試使用

新增測試方法

在UserMapper上加入註解@Mapper表明是持久化映射層,啟動類上加入註解@RestController進行測試,這裏簡單調用一個查詢所有的方法selectAll,啟動類代碼如下:

@SpringBootApplication
@RestController
public class SpringbootGeneratorApplication {

    @Autowired
    private UserMapper userMapper;

    @GetMapping("/findAll")
    public List<User> findAll(){
        return userMapper.selectAll();
    }

    public static void main(String[] args) {
        SpringApplication.run(SpringbootGeneratorApplication.class, args);
    }
}

運行測試

運行項目,瀏覽器訪問localhost:8080/findAll如圖所示:

技術分享圖片

源碼下載 :大老楊碼雲

SpringBoot使用Mybatis-Generator