Java连接数据库 #07# MyBatis Generator简单例子

MyBatis Generator是一个可以帮助我们免去手写实体类&接口类以及XML的代码自动生成工具。

下面,通过一个简单的例子介绍MyBatis Generator如何使用。

 

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

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

}

最后运行测试,能通过应该就没问题了。

posted @ 2019-05-15 12:34  xkfx  阅读(458)  评论(0编辑  收藏  举报