學習了一下調用mybatis-generator插件來實現
- 實體層entity
- dao層接口
- mapper.xml
的快速生成。具體過程如下:
結構圖如下:

1 pom.xml
1.1 添加以下三個依賴
- Spring Boot Mybatis 依賴
- mybatis-generator 依賴【不加generatorConfig.xml文件標紅,生成過程報錯】
- MySQL 連接驅動依賴
1.2 添加了插件mybatis-generator
<?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 https://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.5.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>mybatisGen</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>mybatisGen</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.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Spring Boot Mybatis 依賴 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<!-- mybatis-generator 依賴,不加generatorConfig.xml文件標紅 -->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
</dependency>
<!-- MySQL 連接驅動依賴 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.20</version>
</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>
<!-- 在控制台打印執行日志 -->
<verbose>true</verbose>
<!-- 重復生成時會覆蓋之前的文件-->
<overwrite>true</overwrite>
<!-- 配置文件路徑-->
<configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
</configuration>
<dependencies>
<!-- 數據庫連接選擇8.0以上的,因為用的mysql8.0-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.20</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>
2 建立數據庫
2.1 寫sql文件
首先要確定數據庫里有什么,有幾個表,表里屬性有哪些,數據要不要插入,之后才能在generatorConfig.xml中做相關配置和參數設置。
這里建了數據庫,端口為3306,名字為pili,里面有兩個表,一個為person,一個為show,里面各自有一些屬性和數據格式設置,也插入了一些值,代碼如下:
DROP TABLE IF EXISTS `person`;
CREATE TABLE `person` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主鍵id',
`user_name` varchar(32) DEFAULT NULL COMMENT '角色名',
`user_local` varchar(32) DEFAULT NULL COMMENT '根據地',
`user_sex` varchar(32) DEFAULT NULL,
`nick_name` varchar(32) DEFAULT NULL,
`show_name` varchar(32) DEFAULT NULL COMMENT '劇集名',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
INSERT INTO `person` VALUES (1,'吞佛','異度魔界','男','心機吞','劍蹤');
INSERT INTO `person` VALUES (2,'宵','十二巔','男','宵寶','刀戟');
INSERT INTO `person` VALUES (3,'蒼','玄宗','男','蔥花','奇象');
DROP TABLE IF EXISTS `show`;
CREATE TABLE `show` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主鍵id',
`show_name` varchar(32) DEFAULT NULL COMMENT '劇集名',
`show_year` varchar(32) DEFAULT NULL COMMENT '播放時間',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
INSERT INTO `show` VALUES (1,'劍蹤','2005');
INSERT INTO `show` VALUES (2,'刀戟','2005');
INSERT INTO `show` VALUES (3,'奇象','2006');
2.2 打開數據庫
- cmd以管理員身份運行
net start mysql
mysql -u root -p
輸入密碼
- 打開navcat建立數據庫pili,運行sql文件,刷新,成功實現
3 application.properties
## 數據源配置
# 下面這句話格式很重要,serverTimezone一定要有,如果使用com.mysql.cj.jdbc.Driver的話
# 還要加上useSSL=true保證安全
spring.datasource.url=jdbc:mysql://localhost:3306/pili?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#出錯2——Mybatis配置沒有加
## Mybatis 配置
mybatis.typeAliasesPackage=com.example.mybatisGen.entity
mybatis.mapperLocations=classpath:mapper/*.xml
4 generatorConfig.xml
如果以后經常使用,可以將其設置為代碼模板,以后直接調用。具體步驟如下:
-
【File】-【Settings】-【File and Code Templates】
-
選擇中間的“+”,設置名字和后綴,添加代碼,如圖所示:

-
在resources文件夾下右鍵,new選擇剛剛加上的generatorConfig.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 是逆向工程的主要配置信息 -->
<!-- id:起個名字 -->
<!-- targetRuntime:設置生成的文件適用於那個 mybatis 版本 -->
<context id="default" targetRuntime="MyBatis3">
<!-- 1111111111-->
<!--optional,指在創建class時,對注釋進行控制-->
<commentGenerator>
<!-- 是否去除自動生成日期的注釋 true:是 : false:否 -->
<property name="suppressDate" value="true"/>
<!-- 是否去除自動生成的注釋 true:是 : false:否 -->
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!-- 2222222222-->
<!--jdbc的數據庫連接 wg_insert 為數據庫名字-->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/pili?useUnicode=true&characeterEncoding=utf-8&serverTimezone=UTC"
userId="root"
password="123456">
<!--解決連接到別的數據庫表問題-->
<property name="nullCatalogMeansCurrent" value="true"/>
<!--解決不生成delete、update等-->
<property name="useInformationSchema" value="true"/>
</jdbcConnection>
<!-- 333333333-->
<!--非必須,類型處理器,在數據庫類型和java類型之間的轉換控制-->
<javaTypeResolver>
<!-- 默認情況下數據庫中的 decimal,bigInt 在 Java 對應是 sql 下的 BigDecimal 類 -->
<!-- 不是 double 和 long 類型 -->
<!-- 使用常用的基本類型代替 sql 包下的引用類型 -->
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 444444444-->
<!-- targetPackage:生成的實體類所在的包 -->
<!-- targetProject:生成的實體類所在的硬盤位置 -->
<javaModelGenerator targetPackage="com.example.mybatisGen.entity"
targetProject="src/main/java">
<!-- 是否允許子包 -->
<property name="enableSubPackages" value="false"/>
<!-- 是否對modal添加構造函數 -->
<property name="constructorBased" value="true"/>
<!-- 是否清理從數據庫中查詢出的字符串左右兩邊的空白字符 -->
<property name="trimStrings" value="true"/>
<!-- 建立modal對象是否不可改變 即生成的modal對象不會有setter方法,只有構造方法 -->
<property name="immutable" value="false"/>
</javaModelGenerator>
<!-- 555555555-->
<!-- targetPackage 和 targetProject:生成的 mapper 文件的包和位置 -->
<sqlMapGenerator targetPackage="mapper"
targetProject="src/main/resources">
<!-- 針對數據庫的一個配置,是否把 schema 作為字包名 -->
<property name="enableSubPackages" value="false"/>
</sqlMapGenerator>
<!-- 6666666666-->
<!-- targetPackage 和 targetProject:生成的 interface 文件的包和位置 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.example.mybatisGen.dao" targetProject="src/main/java">
<!-- 針對 oracle 數據庫的一個配置,是否把 schema 作為字包名 -->
<property name="enableSubPackages" value="false"/>
</javaClientGenerator>
<!-- 7777777777-->
<!-- tableName是數據庫中的表名,domainObjectName是生成的JAVA實體名,后面的參數不用改,要生成更多的表就在下面繼續加table標簽 -->
<table tableName="person" domainObjectName="Person"
enableCountByExample="false" enableUpdateByExample="false"
enableDeleteByExample="false" enableSelectByExample="false"
selectByExampleQueryId="false"></table>
<!-- tableName是數據庫中的表名,domainObjectName是生成的JAVA模型名,后面的參數不用改,要生成更多的表就在下面繼續加table標簽 -->
<table tableName="show" domainObjectName="Show"
enableCountByExample="false" enableUpdateByExample="false"
enableDeleteByExample="false" enableSelectByExample="false"
selectByExampleQueryId="false"></table>
</context>
</generatorConfiguration>
5 建立文件夾
建立與generatorConfig.xml里對應的實體層、dao接口層、xml層存放的文件夾,這里建立的是entiey、dao以及resources下的mapper文件夾
6 生成對應文件
找到軟件右邊的Maven,雙擊mybatis-generator:generate,顯示成功即可看到生成了對應的類和接口文件,如圖所示
這里要注意的是,運行一次雙擊后,要再次運行前,需要刪除之前的xml文件,否則就是重復的代碼,實體層和接口層無影響,就是重新生成了一遍,但是之前自己的注釋之類的也沒有了

6.1 自動生成的entity層代碼
6.1.1 Person類
public class Person {
private Long id;
private String userName;
private String userLocal;
private String userSex;
private String nickName;
private String showName;
public Person(Long id, String userName, String userLocal, String userSex, String nickName, String showName) {
this.id = id;
this.userName = userName;
this.userLocal = userLocal;
this.userSex = userSex;
this.nickName = nickName;
this.showName = showName;
}
public Person() {
super();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName == null ? null : userName.trim();
}
public String getUserLocal() {
return userLocal;
}
public void setUserLocal(String userLocal) {
this.userLocal = userLocal == null ? null : userLocal.trim();
}
public String getUserSex() {
return userSex;
}
public void setUserSex(String userSex) {
this.userSex = userSex == null ? null : userSex.trim();
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName == null ? null : nickName.trim();
}
public String getShowName() {
return showName;
}
public void setShowName(String showName) {
this.showName = showName == null ? null : showName.trim();
}
}
6.1.2 Show類
package com.example.mybatisGen.entity;
public class Show {
private Long id;
private String showName;
private String showYear;
public Show(Long id, String showName, String showYear) {
this.id = id;
this.showName = showName;
this.showYear = showYear;
}
public Show() {
super();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getShowName() {
return showName;
}
public void setShowName(String showName) {
this.showName = showName == null ? null : showName.trim();
}
public String getShowYear() {
return showYear;
}
public void setShowYear(String showYear) {
this.showYear = showYear == null ? null : showYear.trim();
}
}
6.2 dao層接口
6.2.1 PersonMapper接口
public interface PersonMapper {
int deleteByPrimaryKey(Long id);
int insert(Person record);
int insertSelective(Person record);
Person selectByPrimaryKey(Long id);
int updateByPrimaryKeySelective(Person record);
int updateByPrimaryKey(Person record);
}
6.2.2 ShowMapper接口
public interface ShowMapper {
int deleteByPrimaryKey(Long id);
int insert(Show record);
int insertSelective(Show record);
Show selectByPrimaryKey(Long id);
int updateByPrimaryKeySelective(Show record);
int updateByPrimaryKey(Show record);
}
6.3 xml文件
6.3.1 PersonMapper.xml
<?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.example.mybatisGen.dao.PersonMapper" >
<resultMap id="BaseResultMap" type="com.example.mybatisGen.entity.Person" >
<constructor >
<idArg column="id" jdbcType="BIGINT" javaType="java.lang.Long" />
<arg column="user_name" jdbcType="VARCHAR" javaType="java.lang.String" />
<arg column="user_local" jdbcType="VARCHAR" javaType="java.lang.String" />
<arg column="user_sex" jdbcType="VARCHAR" javaType="java.lang.String" />
<arg column="nick_name" jdbcType="VARCHAR" javaType="java.lang.String" />
<arg column="show_name" jdbcType="VARCHAR" javaType="java.lang.String" />
</constructor>
</resultMap>
<sql id="Base_Column_List" >
id, user_name, user_local, user_sex, nick_name, show_name
</sql>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long" >
select
<include refid="Base_Column_List" />
from person
where id = #{id,jdbcType=BIGINT}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Long" >
delete from person
where id = #{id,jdbcType=BIGINT}
</delete>
<insert id="insert" parameterType="com.example.mybatisGen.entity.Person" >
insert into person (id, user_name, user_local,
user_sex, nick_name, show_name
)
values (#{id,jdbcType=BIGINT}, #{userName,jdbcType=VARCHAR}, #{userLocal,jdbcType=VARCHAR},
#{userSex,jdbcType=VARCHAR}, #{nickName,jdbcType=VARCHAR}, #{showName,jdbcType=VARCHAR}
)
</insert>
<insert id="insertSelective" parameterType="com.example.mybatisGen.entity.Person" >
insert into person
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="id != null" >
id,
</if>
<if test="userName != null" >
user_name,
</if>
<if test="userLocal != null" >
user_local,
</if>
<if test="userSex != null" >
user_sex,
</if>
<if test="nickName != null" >
nick_name,
</if>
<if test="showName != null" >
show_name,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="id != null" >
#{id,jdbcType=BIGINT},
</if>
<if test="userName != null" >
#{userName,jdbcType=VARCHAR},
</if>
<if test="userLocal != null" >
#{userLocal,jdbcType=VARCHAR},
</if>
<if test="userSex != null" >
#{userSex,jdbcType=VARCHAR},
</if>
<if test="nickName != null" >
#{nickName,jdbcType=VARCHAR},
</if>
<if test="showName != null" >
#{showName,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.example.mybatisGen.entity.Person" >
update person
<set >
<if test="userName != null" >
user_name = #{userName,jdbcType=VARCHAR},
</if>
<if test="userLocal != null" >
user_local = #{userLocal,jdbcType=VARCHAR},
</if>
<if test="userSex != null" >
user_sex = #{userSex,jdbcType=VARCHAR},
</if>
<if test="nickName != null" >
nick_name = #{nickName,jdbcType=VARCHAR},
</if>
<if test="showName != null" >
show_name = #{showName,jdbcType=VARCHAR},
</if>
</set>
where id = #{id,jdbcType=BIGINT}
</update>
<update id="updateByPrimaryKey" parameterType="com.example.mybatisGen.entity.Person" >
update person
set user_name = #{userName,jdbcType=VARCHAR},
user_local = #{userLocal,jdbcType=VARCHAR},
user_sex = #{userSex,jdbcType=VARCHAR},
nick_name = #{nickName,jdbcType=VARCHAR},
show_name = #{showName,jdbcType=VARCHAR}
where id = #{id,jdbcType=BIGINT}
</update>
</mapper>
6.3.2 ShowMapper.xml
<?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.example.mybatisGen.dao.ShowMapper" >
<resultMap id="BaseResultMap" type="com.example.mybatisGen.entity.Show" >
<constructor >
<idArg column="id" jdbcType="BIGINT" javaType="java.lang.Long" />
<arg column="show_name" jdbcType="VARCHAR" javaType="java.lang.String" />
<arg column="show_year" jdbcType="VARCHAR" javaType="java.lang.String" />
</constructor>
</resultMap>
<sql id="Base_Column_List" >
id, show_name, show_year
</sql>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long" >
select
<include refid="Base_Column_List" />
from show
where id = #{id,jdbcType=BIGINT}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Long" >
delete from show
where id = #{id,jdbcType=BIGINT}
</delete>
<insert id="insert" parameterType="com.example.mybatisGen.entity.Show" >
insert into show (id, show_name, show_year
)
values (#{id,jdbcType=BIGINT}, #{showName,jdbcType=VARCHAR}, #{showYear,jdbcType=VARCHAR}
)
</insert>
<insert id="insertSelective" parameterType="com.example.mybatisGen.entity.Show" >
insert into show
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="id != null" >
id,
</if>
<if test="showName != null" >
show_name,
</if>
<if test="showYear != null" >
show_year,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="id != null" >
#{id,jdbcType=BIGINT},
</if>
<if test="showName != null" >
#{showName,jdbcType=VARCHAR},
</if>
<if test="showYear != null" >
#{showYear,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.example.mybatisGen.entity.Show" >
update show
<set >
<if test="showName != null" >
show_name = #{showName,jdbcType=VARCHAR},
</if>
<if test="showYear != null" >
show_year = #{showYear,jdbcType=VARCHAR},
</if>
</set>
where id = #{id,jdbcType=BIGINT}
</update>
<update id="updateByPrimaryKey" parameterType="com.example.mybatisGen.entity.Show" >
update show
set show_name = #{showName,jdbcType=VARCHAR},
show_year = #{showYear,jdbcType=VARCHAR}
where id = #{id,jdbcType=BIGINT}
</update>
</mapper>
7 建立Service層
7.1 PersonService接口&實現類
7.1.1 PersonService接口
public interface PersonService {
int deleteByPrimaryKey(Long id);
int insert(Person record);
int insertSelective(Person record);
Person selectByPrimaryKey(Long id);
int updateByPrimaryKeySelective(Person record);
int updateByPrimaryKey(Person record);
}
7.1.2 PersonService實現類
@Service
public class PersonServiceImpl implements PersonService {
@Resource
private PersonMapper personMapper;
//刪
public int deleteByPrimaryKey(Long id)
{
return personMapper.deleteByPrimaryKey(id);
}
//增
public int insert(Person record)
{
return personMapper.insert(record);
}
//非空增,也就是說,只增加record里面有數據的部分,其余的數據不更新,保存原來的
public int insertSelective(Person record)
{
return personMapper.insertSelective(record);
}
//查
public Person selectByPrimaryKey(Long id)
{
return personMapper.selectByPrimaryKey(id);
}
//更新
public int updateByPrimaryKeySelective(Person record)
{
return personMapper.updateByPrimaryKeySelective(record);
}
public int updateByPrimaryKey(Person record)
{
return personMapper.updateByPrimaryKey(record);
}
}
7.2 ShowService接口&實現類
7.2.1 ShowService接口
public interface ShowService {
int deleteByPrimaryKey(Long id);
int insert(Show record);
int insertSelective(Show record);
Show selectByPrimaryKey(Long id);
int updateByPrimaryKeySelective(Show record);
int updateByPrimaryKey(Show record);
}
7.2.2 ShowService實現類
@Service
public class ShowServiceImpl implements ShowService {
@Autowired
private ShowMapper showMapper;
public int deleteByPrimaryKey(Long id) {
return showMapper.deleteByPrimaryKey(id);
}
public int insert(Show record) {
return showMapper.insert(record);
}
public int insertSelective(Show record) {
return showMapper.insertSelective(record);
}
public Show selectByPrimaryKey(Long id) {
return showMapper.selectByPrimaryKey(id);
}
public int updateByPrimaryKeySelective(Show record) {
return showMapper.updateByPrimaryKeySelective(record);
}
public int updateByPrimaryKey(Show record) {
return showMapper.updateByPrimaryKey(record);
}
}
8 Controller層
/**
* 出錯3——多次使用mybatis-generator造成xml文件代碼重復
* 出錯4——沒有加@RestController
*/
@RestController
public class myController {
@Autowired
private PersonServiceImpl personService;
@Autowired
private ShowServiceImpl showService;
@RequestMapping(value = "/getPerson")
public Person findOnePerson(@RequestParam(value = "id",required = true) long id)
{
return personService.selectByPrimaryKey(id);
}
@RequestMapping(value = "/getShow")
public Show findOneShow(@RequestParam(value = "id",required = true) long id)
{
return showService.selectByPrimaryKey(id);
}
}
9 總結
之前很多次都是直接在別人的examples上改的,這次從頭建立新項目做了一遍,發現了過程中的問題,下面是出錯總結:
- 出錯1——啟動類中@MapperScan沒有加,這個要么加,要么在mapper類中每個類添加@Mapper,可是我兩個都沒有設置
- 出錯2——application.properties中Mybatis配置沒有設置,導致沒有掃描到xml文件
- 出錯3——使用mybatis-generator生成代碼過程中
- 多次使用,這個要再次使用的話,需要將之前的xml文件刪除,否則它會在原來的增刪改查方法上再寫一遍
- 有個特點,實體類和dao層代碼會重新生成覆蓋,之前自己寫的注釋之類也會沒有
- 另外一個特點就是,再次生成后本來自己手寫的實體類還會在,這里的例子是rank實體是我自己寫的,使用generator之后這個類還在,本來還擔心會不會沒有了
- 出錯4——Controller層忘記添加@RestController
- 出錯5——ServiceImpl實現類忘記添加@Service,導致注入失敗
【補充】使用generator生成代碼的過程中,數據庫定義名稱為id,則生成實體類對應也為id,數據庫定義名稱最好為下划線格式,例如user_name,則生成實體類按照駝峰式排列,首字母小寫,此例生成userName
ok,總結完畢!
