天天看点

mybatis-generator自动生成代码示例

在做springboot+mybatis整合中,我们可以通过mybatis自带的mybatis-generator插件自动生成代码,这里有个前提,就是需要在数据库中先生成表,然后根据表来生成实体和dao层代码,以及mybatis的映射文件。

这里介绍如何在idea中,通过配置,一步一步实现代码生成。

1、构建maven工程,修改pom.xml,配置mybatis依赖,以及mybatis-generator插件。

2、设置mapper映射文件生成的地址:application.properties中增加配置。

3、构建数据库以及表结构。

4、设置自动生成代码配置文件。

5、构建maven任务,执行构建。

6、利用构建的结果测试。

===========================================================================

第一步: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>com.xxx.mybatis</groupId>
    <artifactId>mybatis-generate</artifactId>
    <version>1.0</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-test</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.40</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.5</version>
                <dependencies>
                    <dependency>
                        <groupId>org.mybatis.generator</groupId>
                        <artifactId>mybatis-generator-core</artifactId>
                        <version>1.3.5</version>
                    </dependency>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>5.1.40</version>
                    </dependency>
                </dependencies>
                <executions>
                    <execution>
                        <id>mybatis generator</id>
                        <phase>package</phase>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <verbose>true</verbose>
                    <overwrite>true</overwrite>
                    <configurationFile>
                        src/main/resources/mybatis-generator.xml
                    </configurationFile>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
           

第二步:在resources目录下,新建配置文件application.properties,并设置mybatis映射文件生成的地址

server.port=9080
mybatis.mapperLocations=classpath:mapper/*.xml
           

第三步:准备数据库(mybatis)以及表结构

user_info

mysql> desc user_info;
+----------------+--------------+------+-----+---------+-------+
| Field          | Type         | Null | Key | Default | Extra |
+----------------+--------------+------+-----+---------+-------+
| id             | int(11)      | NO   | PRI | NULL    |       |
| name           | varchar(64)  | NO   |     | NULL    |       |
| gender         | tinyint(4)   | NO   |     | NULL    |       |
| age            | int(11)      | NO   |     | NULL    |       |
| mobile         | varchar(11)  | NO   |     | NULL    |       |
| register_mode  | varchar(10)  | NO   |     | NULL    |       |
| third_party_id | varchar(255) | NO   |     | NULL    |       |
+----------------+--------------+------+-----+---------+-------+
7 rows in set (0.00 sec)
           

 user_password

mysql> desc user_password;
+-----------------+--------------+------+-----+---------+-------+
| Field           | Type         | Null | Key | Default | Extra |
+-----------------+--------------+------+-----+---------+-------+
| id              | int(11)      | NO   | PRI | NULL    |       |
| encrpt_password | varchar(255) | NO   |     | NULL    |       |
| user_id         | int(11)      | NO   |     | NULL    |       |
+-----------------+--------------+------+-----+---------+-------+
3 rows in set (0.00 sec)
           

 第四步:配置代码自动生成配置文件,这里需要指定连接数据库,生成实体和dao的位置,以及表与实体的映射关系。

<?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 id="DB2Tables" targetRuntime="MyBatis3">
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/mybatis"
                        userId="hadoop"
                        password="hadoop">
        </jdbcConnection>

        <javaModelGenerator targetPackage="com.xxx.mybatis.domain" targetProject="src/main/java">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>

        <sqlMapGenerator targetPackage="mapper"  targetProject="src/main/resources">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>

        <javaClientGenerator type="XMLMAPPER" targetPackage="com.xxx.mybatis.dao" 
         targetProject="src/main/java">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>

        <table tableName="user_info" domainObjectName="User"
               enableCountByExample="false" enableUpdateByExample="false"
               enableDeleteByExample="false" enableSelectByExample="false"
               selectByExampleQueryId="false">
        </table>
        <table tableName="user_password" domainObjectName="UserPassword"
               enableCountByExample="false" enableUpdateByExample="false"
               enableDeleteByExample="false" enableSelectByExample="false"
               selectByExampleQueryId="false">
        </table>

    </context>
</generatorConfiguration>
           

table中 enableCountByExample=false,enableUpdateByExample=false,enableDeleteByExample=false,enableSelectByExample

=false,selectByExampleQueryId=false,生成的dao的方法中,可以去掉一些跟Example相关的复杂方法,一般的复杂查询,我们可以自己手动编写。

 第五步:构建:IDEA上点击Edit Configurations->新建Maven->填写工程目录working directory以及Command line:mybatis-generator:generate。接着就可以构建了。

mybatis-generator自动生成代码示例

构建以及构建之后生成的文件:

mybatis-generator自动生成代码示例

构建成功打印信息如下:

[INFO] Introspecting table user_info
[INFO] Introspecting table user_password
[INFO] Generating Record class for table user_info
[INFO] Generating Mapper Interface for table user_info
[INFO] Generating SQL Map for table user_info
[INFO] Generating Record class for table user_password
[INFO] Generating Mapper Interface for table user_password
[INFO] Generating SQL Map for table user_password
[INFO] Saving file UserMapper.xml
[INFO] Saving file UserPasswordMapper.xml
[INFO] Saving file User.java
[INFO] Saving file UserMapper.java
[INFO] Saving file UserPassword.java
[INFO] Saving file UserPasswordMapper.java
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.793 s
[INFO] Finished at: 2018-12-11T11:00:42+08:00
[INFO] Final Memory: 15M/305M
[INFO] ------------------------------------------------------------------------
           

第六步:根据生成的代码,验证mybatis与springboot整合。第二步中的配置文件application.properties做修改,增加数据库连接信息。

server.port=9080
mybatis.mapperLocations=classpath:mapper/*.xml
spring.datasource.name=mybatis
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mybatis?useSSL=false
spring.datasource.username=hadoop
spring.datasource.password=hadoop

spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
           

采用数据库连接池:HikariCP,这里配置的数据库信息是给系统使用的,之前在mybatis-generator.xml中配置的数据库信息是给代码生成器使用的。

com.xxx.mybatis目录下新建App.java

package com.xxx.mybatis;

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

@SpringBootApplication
@MapperScan("com.xxx.mybatis.dao")
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class,args);
    }
}
           

新建com.xxx.mybatis.controller包,并在其下新建UserController.java 

package com.xxx.mybatis.controller;

import com.xxx.mybatis.dao.UserMapper;
import com.xxx.mybatis.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @RequestMapping("/get")
    @ResponseBody
    public String get(){
        User user = userMapper.selectByPrimaryKey(1);
        if(user==null){
            return "user is not present.";
        }
        return user.getName();
    }
}
           

启动App.java类,并访问http://localhost:9080/user/get,数据库表user_info中增加一条id=1的记录,再次访问。

mybatis-generator自动生成代码示例

 至此,mybatis-generator插件自动生成代码的示例就完成了,一般的开发中,基本都是先有实体,再有表,而且复杂查询会随着业务的复杂越来越多,仅仅靠插件是无法满足的,这个示例就当学习练手了。