学习了一下调用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,总结完毕!