参考地址 SpringBoot集成MyBatis及使用mybatis-generator-plugin生成代码(完美,步骤巨详细)
一、新建项目
新建步骤没啥好说的,直接上图,按照顺序来即可。
需要注意的是,除了引入web依赖外,还引入了MyBatis和MySQL依赖。
二、pom.xml
2.1 添加连接池依赖
该示例数据库连接池使用阿里的durid,其好处就不多说了,集合了所有连接池的好处,并且还提供了监控等功能,加大了可扩展性等等。
<!--使用durid连接池的依赖-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
1
2
3
4
5
6
2.2 添加mybatis-generator插件及相关依赖
此处,除了需要添加mybatis-generator-maven-plugin插件外,还需要添加mysql-connector及mybatis-generator-core等依赖,方面后面再使用插件生成pojo和mapper文件时使用。如下:
<!-- mybatis generator 自动生成代码插件 -->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<configuration>
<configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
<overwrite>true</overwrite>
<verbose>true</verbose>
</configuration>
<!-- 配置数据库链接及mybatis generator core依赖 生成mapper时使用 -->
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.2</version>
</dependency>
</dependencies>
</plugin>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2.3 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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.happy.video</groupId>
<artifactId>small_video</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>small_video</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<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>
<!--需要手动添加的依赖-->
<!--使用durid连接池的依赖-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.1</version>
</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.2</version>
<configuration>
<configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
<overwrite>true</overwrite>
<verbose>true</verbose>
</configuration>
<!-- 配置数据库链接及mybatis generator core依赖 生成mapper时使用 -->
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.2</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>
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
83
84
85
三、application.properties或application.yml配置
接下来就需要对application进行相关设置了,此处以application.yml为例,其与.properties配置项没区别,只不过语法稍微不一样而已。
此处不再一一展开,直接上配置文件,相关配置都有注释,可自行阅读:
# 设置端口
server:
port: 8080
# 设置数据源
spring:
datasource:
url: jdbc:mysql://localhost:3306/sb_mbg_demo
username: root
password: root
# 连接池类型
type: com.alibaba.druid.pool.DruidDataSource
# 驱动
driver-class-name: com.mysql.jdbc.Driver
# 连接池配置
druid:
# 最小数
min-idle: 5
# 最大数
max-active: 20
# 初始大小
initial-size: 5
# 配置获取连接等待超时时间
max-wait: 6000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
time-between-eviction-runs-millis: 60000
# 配置一个连接在池中最小生存时间 单位为毫秒
min-evictable-idle-time-millis: 300000
validation-query: SELECT 1 FROM DUAL
test-while-idle: true
test-on-borrow: false
test-on-return: false
# 打开 PSCache,并且指定每个连接上PSCache的大小
pool-prepared-statements: true
max-pool-prepared-statement-per-connection-size: 20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,wall用于防火墙
filters: stat,wall
# 配置mybatis
mybatis:
mapper-locations: classpath:mappers/*.xml
# 全局的映射,不用在xml文件写实体类的全路径
type-aliases-package: com.happy.video.pojo
configuration:
# 开启驼峰映射
map-underscore-to-camel-case: true
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
四、mybatis-generator插件配置
4.1 generatorConfig.xml配置
不知道是否还记得在pom.xml中mybatis-generator-plugin中有过这样配置
<configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
1
2
其实这个就是其配置文件,根据配置,在resources目录下新建generator文件夹,并新建generatorConfig.xml配置文件。
该配置文件主要描述如下信息:数据库连接配置、类型转换、生成模型的包名及位置、生成映射文件的包名及位置、生成mapper文件的包名及位置、要生成的表等。
废话不多说,直接上代码,具体都有注释,可自行阅读:
<?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">
<commentGenerator>
<property name="suppressDate" value="true"/>
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!-- 数据库链接URL,用户名、密码 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/sb_mbg_demo"
userId="root"
password="root">
</jdbcConnection>
<!-- 类型转换 -->
<javaTypeResolver>
<!-- 是否使用BigDecimals,false可自动转化以下类型(Long Integer Short等) -->
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 生成模型的包名和位置-->
<javaModelGenerator targetPackage="com.happy.video.pojo" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- 生成映射文件的包名和位置-->
<sqlMapGenerator targetPackage="mappers" targetProject="src/main/resources">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!-- 生成DAO的包名和位置 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.happy.video.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">
<property name="useActualColumnNames" value="false"/>
<!-- 数据库表主键 -->
<generatedKey column="id" sqlStatement="Mysql" identity="true"/>
</table>
</context>
</generatorConfiguration>
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
4.2 创建mybatis-generator命令快捷方式
该步骤是为了方便在后续直接通过运行命令方式来操作生成mapper、pojo等,就像运行application一样。
操作步骤如下:
选中Edit Configurations,打开如下窗口:
如果此处没有Maven条目,需要点击右上角加号,选中Maven:
在右侧Command line中输入命令mybatis-generator:generate -e,并设置其Name,如下:
此时,设置完成,点击OK即可。
五、数据库相关
5.1 创建数据库
CREATE DATABASE sb_myb_demo charset utf8;
1
5.2 创建表
CREATE TABLE user(
user_id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
user_name VARCHAR(255) NOT NULL ,
password VARCHAR(255) NOT NULL ,
phone VARCHAR(255) NOT NULL
) ENGINE=INNODB AUTO_INCREMENT=1000 DEFAULT CHARSET=utf8;
1
2
3
4
5
6
六、执行generate,生成pojo及mapper
执行之前设置的generate命令,运行结果如下:
/Library/Java/JavaVirtualMachines/jdk1.8.0_111.jdk/Contents/Home/bin/java -Dmaven.multiModuleProjectDirectory=/Users/zhonglongquan/Project/IdeaProjects "-Dmaven.home=/Applications/IntelliJ IDEA.app/Contents/plugins/maven/lib/maven3" "-Dclassworlds.conf=/Applications/IntelliJ IDEA.app/Contents/plugins/maven/lib/maven3/bin/m2.conf" -Didea.launcher.port=7536 "-Didea.launcher.bin.path=/Applications/IntelliJ IDEA.app/Contents/bin" -Dfile.encoding=UTF-8 -classpath "/Applications/IntelliJ IDEA.app/Contents/plugins/maven/lib/maven3/boot/plexus-classworlds-2.5.2.jar:/Applications/IntelliJ IDEA.app/Contents/lib/idea_rt.jar" com.intellij.rt.execution.application.AppMain org.codehaus.classworlds.Launcher -Didea.version=2016.3.5 mybatis-generator:generate -e
[INFO] Error stacktraces are turned on.
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building small_video 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- mybatis-generator-maven-plugin:1.3.2:generate (default-cli) @ small_video ---
[INFO] Connecting to the Database
[INFO] Introspecting table user
log4j:WARN No appenders could be found for logger (org.mybatis.generator.internal.db.DatabaseIntrospector).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
[INFO] Generating Record class for table user
[INFO] Generating Mapper Interface for table user
[INFO] Generating SQL Map for table user
[INFO] Saving file UserMapper.xml
[INFO] Saving file User.java
[INFO] Saving file UserMapper.java
[WARNING] Column id, specified as an identity column in table user, does not exist in the table.
[WARNING] Existing file /Users/***/Project/IdeaProjects/small_video/src/main/java/com/happy/video/pojo/User.java was overwritten
[WARNING] Existing file /Users/***/Project/IdeaProjects/small_video/src/main/java/com/happy/video/mapper/UserMapper.java was overwritten
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.279 s
[INFO] Finished at: 2019-01-10T17:56:32+08:00
[INFO] Final Memory: 15M/155M
[INFO] ------------------------------------------------------------------------
Process finished with exit code 0
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
然后查看项目,发现mapper、pojo等已经生成好,并且生成了相关CRUD方法,如图:
生成代码就不在此罗列了,可自行尝试或者查看文章尾部的示例。
七、编写Controller、Service
7.1 编写Service
新建service包及UserService接口,此处偷懒,直接复制UserMapper的方法了,内容如下:
package com.happy.video.service;
import com.happy.video.pojo.User;
/**
* Created by *** on 2019/1/10.
*/
public interface UserService {
int deleteByPrimaryKey(Integer userId);
int insert(User record);
int insertSelective(User record);
User selectByPrimaryKey(Integer userId);
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
在service包下新建impl包及UserServiceImpl类,如下:
package com.happy.video.service.impl;
import com.happy.video.mapper.UserMapper;
import com.happy.video.pojo.User;
import com.happy.video.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* Created by *** on 2019/1/10.
*/
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public int deleteByPrimaryKey(Integer userId) {
return userMapper.deleteByPrimaryKey(userId);
}
@Override
public int insert(User record) {
return userMapper.insert(record);
}
@Override
public int insertSelective(User record) {
return userMapper.insertSelective(record);
}
@Override
public User selectByPrimaryKey(Integer userId) {
return userMapper.selectByPrimaryKey(userId);
}
@Override
public int updateByPrimaryKeySelective(User record) {
return userMapper.updateByPrimaryKeySelective(record);
}
@Override
public int updateByPrimaryKey(User record) {
return userMapper.updateByPrimaryKey(record);
}
}
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
此时,注入的userMapper会报错,无视即可。
7.2 新建controller
新建controller及UserController类,如下:
package com.happy.video.controller;
import com.happy.video.pojo.User;
import com.happy.video.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by *** on 2019/1/10.
*/
@RestController()
@RequestMapping("/user")
public class UserController {
@Autowired
private UserServiceImpl userService;
@RequestMapping("index")
public String index() {
return "hello user";
}
@RequestMapping("/queryUserById")
public User selectUserById(int id) {
System.out.println("id:" + id);
User user = userService.selectByPrimaryKey(id);
System.out.println(user.toString());
return user;
}
}
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
八、SpringBootApplication入口类设置
在应用入口类添加@MapperScan注解,并指定要扫描的包,此处如果不加的话,需要在自动生成的mapper类中,添加@Mapper注解,这样就添加的太繁琐,建议使用@MapperScan注解的形式。
修改后的SmallVideoApplication.java内容如下:
package com.happy.video;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.happy.video.mapper")
public class SmallVideoApplication {
public static void main(String[] args) {
SpringApplication.run(SmallVideoApplication.class, args);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
九、启动测试
9.1 启动应用
执行入口类的main方法,启动应用
9.2 访问controller映射的方法
之前在UserController中,添加了查询用户queryUserById的方法,那就来访问一下吧,在浏览器访问链接为:http://localhost:8080/user/queryUserById?id=1
(之前偷偷在数据库添加了一条记录)
显示结果如下:
十、大功告成
到此,SpringBoot集成Mybatis以及使用mybatis-generator插件生成mapper、pojo等已经完成,不得不说该插件大大减少了我们的工作量,爽的一批。
、