SpringBoot2 | 第十篇:Mybatis代码生成器

SpringBoot 2.0 中如何使用代码生成器

[TOC]

环境/版本一览:

  • 开发工具:Intellij IDEA 2018.2.2
  • springboot: 2.0.5.RELEASE
  • jdk:1.8.0_171
  • maven:3.3.9
  • generator:1.3.5

1、搭建

1538728808890

2、pom.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<dependencies>
<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.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!-- mybatis generator 自动生成代码插件 -->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.5</version>
<configuration>
<configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
<overwrite>true</overwrite>
<verbose>true</verbose>
</configuration>
</plugin>
</plugins>
</build>

3、application.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
server:
port: 8080

spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
# 基本属性 allowMultiQueries:设置为true后,数据库那边才允许你批量更新。编码属性设置了存储数据到数据库才不会是乱码
url: jdbc:mysql://localhost:3306/chapter10?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&serverTimezone=UTC&useSSL=false
username: root
password: 123456
# 下面为连接池的补充设置,应用到上面所有数据源中
hikari:
# 表示连接池的用户定义名称,主要显示在日志记录和JMX管理控制台中,以标识池和池配置。
pool-name: HikariPool
# 控制客户端(即您)等待池中连接的最大毫秒数。如果在没有连接可用的情况下超过此时间,则将抛出SQLException。最低可接受的连接超时为250毫秒。 默认值:30000(30秒)
connection-timeout: 3000
# 控制允许连接在池中空闲的最长时间。默认值:600000(10分钟)
idle-timeout: 600000
# 控制池中连接的最长生命周期。默认值:1800000(30分钟)
max-lifetime: 1800000

mybatis:
mapper-locations: classpath:mapper/*.xml # 注意:一定要对应 mapper 映射xml文件的所在路径
type-aliases-package: com.fatal.entity # 注意:对应实体类的路径
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 可以自控制台上输出 sql 语句

4、sql

1
2
3
4
5
6
CREATE TABLE `user`(
`id` INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
`username` VARCHAR(255) NOT NULL ,
`password` VARCHAR(255) NOT NULL ,
`phone` VARCHAR(255) NOT NULL
) ENGINE=INNODB AUTO_INCREMENT=1000 DEFAULT CHARSET=utf8;

5、使用mybatis generator 自动生成代码

  • 往项目中添加generatorConfig.xml 文件。可以把下面的配置复制下去改

12212121212121

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<?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>
<!-- 数据库驱动:选择你的本地硬盘上面的数据库驱动包-->
<classPathEntry location="E:\mysql\lib\mysql-connector-java-5.1.46.jar"/>
<context id="DB2Tables" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressDate" value="true"/>
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!--数据库链接URL,用户名、密码 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://127.0.0.1/chapter10"
userId="root"
password="123456">
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 生成模型的包名和位置-->
<javaModelGenerator targetPackage="com.fatal.entity" 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>
<!-- 生成DAO的包名和位置-->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.fatal.mapper" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->
<table tableName="user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
</context>
</generatorConfiguration>

注意:

  1. 如果上面的 “http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" 报红线

解决方式如下:FIle->Setting->Languages&Frameworks->Schemas and DTDs

  1. mysql jar 包可以去 maven 仓库取,所以在配置文件中的路径你可以直接给 maven仓库 对应版本 jar包 的路径。

123515153451435

12361436413616143

  • 点击run-Edit Configurations

1325123521352315

  • 添加配置

    20170816144723793

  • 运行

注意!!!同一张表一定不要运行多次,因为mapper的映射文件中会生成多次的代码,导致报错,==切记==

20170816144801010

最后生成的文件以及结构:

1538730622285

6、生成的文件

User.java

我用 @Data 方法把生成的 getset 替代了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.fatal.entity;

import lombok.Data;
import lombok.experimental.Accessors;

@Data
@Accessors(chain = true)
public class User {

private Integer id;

private String username;

private String password;

private String phone;

}

UserMapper.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package com.fatal.mapper;

import com.fatal.entity.User;

public interface UserMapper {
int deleteByPrimaryKey(Integer id);

int insert(User record);

int insertSelective(User record);

User selectByPrimaryKey(Integer id);

int updateByPrimaryKeySelective(User record);

int updateByPrimaryKey(User record);
}

UserMapper.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
<?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.fatal.mapper.UserMapper">
<resultMap id="BaseResultMap" type="com.fatal.entity.User">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="username" jdbcType="VARCHAR" property="username" />
<result column="password" jdbcType="VARCHAR" property="password" />
<result column="phone" jdbcType="VARCHAR" property="phone" />
</resultMap>
<sql id="Base_Column_List">
id, username, password, phone
</sql>
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from user
where id = #{id,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
delete from user
where id = #{id,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.fatal.entity.User">
insert into user (id, username, password,
phone)
values (#{id,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},
#{phone,jdbcType=VARCHAR})
</insert>
<insert id="insertSelective" parameterType="com.fatal.entity.User">
insert into user
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
</if>
<if test="username != null">
username,
</if>
<if test="password != null">
password,
</if>
<if test="phone != null">
phone,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=INTEGER},
</if>
<if test="username != null">
#{username,jdbcType=VARCHAR},
</if>
<if test="password != null">
#{password,jdbcType=VARCHAR},
</if>
<if test="phone != null">
#{phone,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.fatal.entity.User">
update user
<set>
<if test="username != null">
username = #{username,jdbcType=VARCHAR},
</if>
<if test="password != null">
password = #{password,jdbcType=VARCHAR},
</if>
<if test="phone != null">
phone = #{phone,jdbcType=VARCHAR},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.fatal.entity.User">
update user
set username = #{username,jdbcType=VARCHAR},
password = #{password,jdbcType=VARCHAR},
phone = #{phone,jdbcType=VARCHAR}
where id = #{id,jdbcType=INTEGER}
</update>
</mapper>

7、启动类添加Mapper扫描

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.fatal;

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

@SpringBootApplication
@MapperScan("com.fatal.mapper")
public class Chapter10Application {

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

8、Test

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package com.fatal.mapper;

import com.fatal.entity.User;
import org.junit.Assert;
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;

/**
* @author: Fatal
* @date: 2018/10/5 0005 16:09
*/
@SpringBootTest
@RunWith(SpringRunner.class)
public class UserMapperTest {

@Autowired
private UserMapper mapper;

@Test
public void deleteByPrimaryKey() {
int record = mapper.deleteByPrimaryKey(1001);
Assert.assertNotEquals(0, record);
}

@Test
public void insert() {
User user = new User().setUsername("米彩").setPassword("123").setPhone("123");
int record = mapper.insert(user);
Assert.assertNotEquals(0, record);
}

@Test
public void insertSelective() {
User user = new User().setUsername("米彩").setPassword("123");
int record = mapper.insert(user);
Assert.assertNotEquals(0, record);
}

/**
* select id, user_name, password, phone from user where id = ?
*/
@Test
public void selectByPrimaryKey() {
User user = mapper.selectByPrimaryKey(1000);
Assert.assertNotEquals(null, user);
}

/**
* Preparing: update user SET user_name = ?, password = ? where id = ?
* Parameters: 米彩的姐姐(String), 123(String), 1000(Integer)
*/
@Test
public void updateByPrimaryKeySelective() {
User user = new User().setId(1000).setUsername("米彩的姐姐").setPassword("123");
int record = mapper.updateByPrimaryKeySelective(user);
Assert.assertNotEquals(0, record);
}

/**
* Preparing: update user set user_name = ?, password = ?, phone = ? where id = ?
* Parameters: 米彩的姐姐(String), 123(String), null, 1000(Integer)
*/
@Test
public void updateByPrimaryKey() {
User user = new User().setId(1000).setUsername("米彩的姐姐").setPassword("123");
int record = mapper.updateByPrimaryKey(user);
Assert.assertNotEquals(0, record);
}
}

总结

SpringBoot的知识已经有前辈在我们之前探索了。比较喜欢的博主有:唐亚峰 | Battcn方志朋的专栏程序猿DD纯洁的微笑。对这门技术感兴趣的可以去他们的博客逛逛。谢谢他们的分享~~

以上文章是我用来学习的Demo,都是基于 SpringBoot2.x 版本。

源码地址: https://github.com/ynfatal/springboot2-learning/tree/master/chapter10

学习 LuisChen 前辈的经验