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

MyBatis Generator是一個能夠幫助咱們免去手寫實體類&接口類以及XML的代碼自動生成工具。html

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

 

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

 

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

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);

 

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

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

 

四、編寫MyBatis Generator的配置文件。數據庫

我通常這這樣佈局文件:apache

mybatis-generator.xml:json

<?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.htmlmybatis

 

五、經過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

運行成功長這個樣:

自動生成的文件:

 

六、測試一下。

編寫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());
    }

}

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

相關文章
相關標籤/搜索