概述
MyBatis Generator (简称 MBG) 是一个用于 MyBatis和 iBATIS的代码生成器。它可以为 MyBatis的所有版本以及 2.2.0之后的 iBATIS版本自动生成 ORM层代码,典型地包括我们日常需要手写的 POJO、mapper xml 以及 mapper 接口等。MyBatis Generator 自动生成的 ORM层代码几乎可以应对大部分 CRUD 数据表操作场景,可谓是一个生产力工具啊!
数据库准备与工程搭建
- 创建要生成代码的数据库表,我的数据库是mysql 5.7
/*==============================================================*/
/* Table: department */
/*==============================================================*/
create table department
(
id INT8 not null,
dept_name varchar(20) comment '部门名称',
descr varchar(100) comment '部门描述',
create_time timestamp,
primary key (id)
);
/*==============================================================*/
/* Table: employee */
/*==============================================================*/
create table employee
(
id INT8 not null,
name varchar(20) comment '部门名称',
age varchar(100) comment '部门描述',
gender INT2,
dept_id INT8,
address varchar(100),
create_time timestamp,
primary key (id)
);
- 新建一个Spring Boot工程
- 在pom.xml添加插件
<plugin>
<!--Mybatis-generator插件,用于自动生成Mapper和POJO-->
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.7</version>
<configuration>
<!--配置文件的位置-->
<configurationFile>src/main/resources/mybatis-generator-config.xml</configurationFile>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
<executions>
<execution>
<id>Generate MyBatis Artifacts</id>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.40</version>
</dependency>
<!--生成代码插件-->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.7</version>
</dependency>
</dependencies>
</plugin>
- application.yml 配置文件
spring:
jmx:
default-domain: mybatis
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/mybatis-demo?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
username: root
password: root
mybatis:
# 指定实体类包路径
typeAliasesPackage: com.wg.demo.po
# 指定xml文件扫描路径
mapper-locations: classpath*:mapper/*.xml
如果你的驱动名称是 com.mysql.jdbc.Driver,它可能会报错,原因是mysql版本不匹配,改成com.mysql.cj.jdbc.Driver即可
如果你有时区问题,可以尝试网上清一色的回答url后面添加 serverTimezone=UTC ,但是我改了不行,用serverTimezone=Asia/Shanghai就可以。
如果你警告 建立ssl的问题,这也是5+版本的问题,同样url后面添加 useSSL=false 即可,别忘了配置generator的xml文件里也要添加一次。
- springboot 启动类上添加 @MapperScan({"com.example.demo.dao"}),根据自己的地址改动。
- resources下新建mybatis-generator-config.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="context" targetRuntime="MyBatis3">
<plugin type="org.mybatis.generator.plugins.UnmergeableXmlMappersPlugin"/>
<commentGenerator>
<property name="suppressAllComments" value="true"/>
<property name="suppressDate" value="true"/>
</commentGenerator>
<!-- 数据库的相关配置 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/test?useSSL=false" userId="root" password="123456"/>
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 实体类生成的位置 -->
<javaModelGenerator targetPackage="com.example.demo.po" targetProject="src/main/java">
<property name="enableSubPackages" value="false"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- *Mapper.xml 文件的位置 -->
<sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
<property name="enableSubPackages" value="false"/>
</sqlMapGenerator>
<!-- Mapper 接口文件的位置 -->
<javaClientGenerator targetPackage="com.example.demo.dao" targetProject="src/main/java" type="XMLMAPPER">
<property name="enableSubPackages" value="false"/>
</javaClientGenerator>
<!-- 相关表的配置 -->
<table tableName="employee" domainObjectName="Employee" enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false" enableUpdateByExample="false"/>
<table tableName="department" domainObjectName="Department" enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false" enableUpdateByExample="false"/>
</context>
</generatorConfiguration>
- 配置启动类
启动后就自动生成了dao、po和mapper
- 编写controller
@RestController
@RequestMapping("/employee")
public class EmployeeController {
@Autowired
private EmployeeMapper employeeMapper;
@GetMapping("/get/{id}")
public RetResult getById(@PathVariable(value="id") Long id){
Employee employee = employeeMapper.selectByPrimaryKey(id);
return RetResponse.makeOKRsp(employee);
}
@PostMapping("/del/{id}")
public RetResult delById(@PathVariable(value="id") Long id){
int result = employeeMapper.deleteByPrimaryKey(id);
return RetResponse.makeRsp(result,"删除成功");
}
@PostMapping("/new")
public RetResult newEmployee(@RequestBody Employee employee){
int result = employeeMapper.insert(employee);
return RetResponse.makeRsp(result, "添加成功");
}
@PostMapping("/update")
public RetResult updateEmployee(@RequestBody Employee employee){
int result = employeeMapper.updateByPrimaryKeySelective(employee);
return RetResponse.makeRsp(result, "更新成功");
}
}
- common中的三个Ret类
package com.example.demo.common;
public enum RetCode {
// 成功
SUCCESS(200),
// 失败
FAIL(400),
// 未认证(签名错误)
UNAUTHORIZED(401),
// 接口不存在
NOT_FOUND(404),
// 服务器内部错误
INTERNAL_SERVER_ERROR(500);
public int code;
RetCode(int code) {
this.code = code;
}
}
-----------------------------------------------------------------
package com.example.demo.common;
public class RetResponse {
private final static String SUCCESS = "success";
public static <T> RetResult<T> makeOKRsp() {
return new RetResult<T>().setCode(RetCode.SUCCESS).setMsg(SUCCESS);
}
public static <T> RetResult<T> makeOKRsp(T data) {
return new RetResult<T>().setCode(RetCode.SUCCESS).setMsg(SUCCESS).setData(data);
}
public static <T> RetResult<T> makeErrRsp(String message) {
return new RetResult<T>().setCode(RetCode.FAIL).setMsg(SUCCESS);
}
public static <T> RetResult<T> makeRsp(int code, String msg) {
return new RetResult<T>().setCode(code).setMsg(msg);
}
public static <T> RetResult<T> makeRsp(int code, String msg, T data) {
return new RetResult<T>().setCode(code).setMsg(msg).setData(data);
}
}
---------------------------------------------------------------------
package com.example.demo.common;
import com.alibaba.fastjson.JSON;
public class RetResult<T> {
public int code;
private String msg;
private T data;
public RetResult<T> setCode(RetCode retCode) {
this.code = retCode.code;
return this;
}
public int getCode() {
return code;
}
public RetResult<T> setCode(int code) {
this.code = code;
return this;
}
public String getMsg() {
return msg;
}
public RetResult<T> setMsg(String msg) {
this.msg = msg;
return this;
}
public T getData() {
return data;
}
public RetResult<T> setData(T data) {
this.data = data;
return this;
}
}
参考文献
Q.E.D.