1. 程式人生 > >Java連接數據庫 #07# MyBatis Generator簡單例子

Java連接數據庫 #07# MyBatis Generator簡單例子

autowire 元素 display 1.3 fig exceptio 解釋 enables play

MyBatis Generator是一個可以幫助我們免去手寫實體類&接口類的代碼自動生成工具。

下面,通過一個簡單的例子介紹MyBatis Generator如何使用。

大體流程如下:

  1. 創建項目
  2. 創建數據表
  3. 添加依賴
  4. 編寫MyBatis Generator的配置文件
  5. 通過Maven插件來跑MyBatis Generator
  6. 測試一下

1、首先用IntelliJ IDEA創建一個最簡單的Maven項目

2、創建一張簡單的數據表(我這裏用的數據庫是MySQL),並插入幾條記錄,以便之後測試:

CREATE DATABASE jee_ex9;
USE jee_ex9; CREATE TABLE student_info ( id BIGINT NOT NULL AUTO_INCREMENT, name VARCHAR(50) NOT NULL, age INT NOT NULL, score INT NOT NULL , PRIMARY KEY (id) ) ENGINE=InnoDB AUTO_INCREMENT=1000 DEFAULT CHARSET=utf8; -- SET NAMES gbk; INSERT INTO student_info(name, age, score)
VALUES ("student1", 12, 82), ("student2", 21, 62);

3、添加Spring Boot-MyBatis相關的依賴:

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.5.RELEASE</version
> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>com.jayway.jsonpath</groupId> <artifactId>json-path</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>6.0.6</version> </dependency> <!-- https://mvnrepository.com/artifact/com.alibaba/druid --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.6</version> </dependency> <!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency> </dependencies> <properties> <java.version>1.8</java.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties>

4、編寫MyBatis Generator的配置文件。

我一般這這樣布局文件:

技術分享圖片

mybatis-generator.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>
    <!-- 可以定義多個context元素以允許從多個數據庫中生成對象 -->
    <context id="DB2Tables" targetRuntime="MyBatis3">
        <!-- jdbcConnection元素定義了連接相應數據庫所必要的信息 -->
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://127.0.0.1:3306/jee_ex9?useUnicode=true&amp;characterEncoding=utf8&amp;useJDBCCompliantTimezoneShift=true&amp;useLegacyDatetimeCode=false&amp;serverTimezone=Asia/Shanghai"
                        userId="root"
                        password="19971019">
            <!-- [WARNING] Cannot obtain primary key information from the database, generated objects may be incomplete -->
            <property name="nullCatalogMeansCurrent" value="true" />
        </jdbcConnection>

        <!-- javaModelGenerator定義如何生成實體類,例如生成到哪個包下,項目路徑等 -->
        <javaModelGenerator targetPackage="jee_ex9.model" targetProject="src/main/java">
            <!-- enableSubPackages屬性決定MBG是否會根據自檢表(the introspected table)的目錄和模式為對象生成不同的Java包 -->
            <property name="enableSubPackages" value="true" />
            <!-- 當設置trimStrings為true時,MBG會增加代碼以處理從數據庫返回的字符串 -->
            <property name="trimStrings" value="true" />
        </javaModelGenerator>

        <!-- sqlMapGenerator定義如何生成xml文件 -->
        <sqlMapGenerator targetPackage="mapping"  targetProject="src/main/resources">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>

        <!-- javaClientGenerator定義如何生成DAO層的類和接口 -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="jee_ex9.dao"  targetProject="src/main/java">
            <!-- XMLMAPPER定義了生成的對象是Java接口,該接口依賴於自動生成的xml文件 -->
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>

        <!--
        tableName定義表名
        domainObjectName定義領域對象名字,
        enableXxByExample將生成一些復雜的數據操作的示例代碼,
        但我們實際較少用到,並且即便要用,也是自己去手動寫,所以disable掉。-->
        <table tableName="student_info" domainObjectName="StudentInfo"
               enableCountByExample="false" enableUpdateByExample="false"
               enableDeleteByExample="false" enableSelectByExample="false"
               selectByExampleQueryId="false" />
    </context>
</generatorConfiguration>

對每個元素的詳細解釋,參考官方文檔:http://www.mybatis.org/generator/configreference/xmlconfig.html

5、通過Maven插件來跑MyBatis Generator。

首先需要在pom.xml中添加相應插件,完整的pom.xml如下:

技術分享圖片
<?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>org.sample</groupId>
    <artifactId>jee_ex9</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.5.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.jayway.jsonpath</groupId>
            <artifactId>json-path</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.6</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.6</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
    </dependencies>

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

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>

            <!-- 通過mvn mybatis-generator:generate運行該插件,MBG將根據配置文件自動生成相應文件 -->
            <!-- 可以添加一些標準命令行參數,例如:mvn -Dmybatis.generator.overwrite=true mybatis-generator:generate -->
            <!-- mybatis.generator.overwrite覆蓋已存在的java文件 -->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.7</version>
                <dependencies>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>6.0.6</version>
                    </dependency>
                </dependencies>
                <configuration>
                    <configurationFile>src/main/resources/mybatis-generator.xml</configurationFile>
                    <verbose>true</verbose>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
View Code

執行該插件:

mvn mybatis-generator:generate

運行成功長這個樣:

技術分享圖片

自動生成的文件:

技術分享圖片

6、測試一下。

編寫Spring Boot應用的程序入口:

package jee_ex9;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("jee_ex9.dao") // 省得在每個DAO接口上寫@Mapper註解
public class Application {

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

編寫Spring Boot配置文件(直接拷貝之前寫的):

server.port=8090
mybatis.mapper-locations=classpath:mapping/*.xml

spring.datasource.name=jee_ex9_datasource
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/jee_ex9?useUnicode=true&characterEncoding=utf8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=19971019

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

編寫測試類:

package jee_ex9.dao;

import jee_ex9.model.StudentInfo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import static org.junit.Assert.*;

@RunWith(SpringRunner.class)
@SpringBootTest
public class StudentInfoMapperTest {

    @Autowired
    private StudentInfoMapper mapper;

    @Test
    public void selectByPrimaryKey() throws Exception {
        StudentInfo info = mapper.selectByPrimaryKey(1000L);
        assertEquals("student1", info.getName());
    }

}

最後運行測試,能通過應該就沒問題了。

Java連接數據庫 #07# MyBatis Generator簡單例子