1:pom
<?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>3.2.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.zd</groupId>
<artifactId>code_generator</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Mybatis-Plus-Generator</name>
<description>Mybatis-Plus-Generator</description>
<properties>
<java.version>17</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-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</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>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.3</version>
<exclusions>
<exclusion>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>3.0.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-generator -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.5.3</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2:启动类以及application.yml
@SpringBootApplication
public class MybatisPlusGeneratorApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisPlusGeneratorApplication.class, args);
}
/**
* 解决:org.springframework.beans.factory.BeanNotOfRequiredTypeException:
* Bean named 'ddlApplicationRunner' is expected to be of type 'org.springframework.boot.Runner'
* but was actually of type 'org.springframework.beans.factory.support.NullBean'
* 的报错
* @param ddlList
* @return
*/
@Bean
public DdlApplicationRunner ddlApplicationRunner(@Autowired(required = false) List ddlList) {
return new DdlApplicationRunner(ddlList);
}
}
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/aaa?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false&allowMultiQueries=true&serverTimezone=GMT%2b8
username: root
password: 123456
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
mapper-locations: classpath*:/mapper/**/*.xml
3:代码生成主类
package com.zd.generator;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.fill.Column;
import com.baomidou.mybatisplus.generator.fill.Property;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class CodeGeneratorVelocity {
// 数据库url
public static final String MYSQL_URL = "jdbc:mysql://localhost:3306/aaa?serverTimezone=GMT%2B8";
// 数据库登录名
public static final String MYSQL_UAERNAME = "root";
// 数据库密码
public static final String MYSQL_PASSWORD = "123456";
// 代码 作者
public static final String AUTHOR = "zd";
// 父类包名
public static final String PARENT_PACKAGE = "com.zd";
// 需要生成代码的数据表名
public static final String TABLE_NAME = "tb_account";
public static void main(String[] args) {
// 数据源配置
FastAutoGenerator.create(MYSQL_URL, MYSQL_UAERNAME, MYSQL_PASSWORD)
.globalConfig(builder -> {
builder.author(AUTHOR) // 设置作者
// .enableSwagger() // 开启 swagger 模式 默认值:false
.disableOpenDir() // 禁止打开输出目录 默认值:true
.commentDate("yyyy-MM-dd") // 注释日期
.dateType(DateType.ONLY_DATE) //定义生成的实体类中日期类型 DateType.ONLY_DATE 默认值: DateType.TIME_PACK
.outputDir(System.getProperty("user.dir") + "/src/main/java"); // 指定输出目录
})
.packageConfig(builder -> {
builder.parent(PARENT_PACKAGE) // 父包模块名
.controller("controller") //Controller 包名 默认值:controller
.entity("entity") //Entity 包名 默认值:entity
.service("service") //Service 包名 默认值:service
.mapper("dao") //Mapper 包名 默认值:mapper
.pathInfo(Collections.singletonMap(OutputFile.xml, System.getProperty("user.dir") + "/src/main/resources/mapper")); // 设置mapperXml生成路径//默认存放在mapper的xml下
})
.injectionConfig(consumer -> {
Map<String, String> customFile = new HashMap<>();
consumer.customFile(customFile);
})
.strategyConfig(builder -> {
builder.addInclude(TABLE_NAME) // 设置需要生成的表名 可边长参数“user”, “user1”
.addTablePrefix("tb_") // 设置过滤表前缀
.serviceBuilder()//service策略配置
.formatServiceFileName("%sService")
.formatServiceImplFileName("%sServiceImpl")
.entityBuilder()// 实体类策略配置
.idType(IdType.ASSIGN_ID)//主键策略 雪花算法自动生成的id
.addTableFills(new Column("create_time", FieldFill.INSERT)) // 自动填充配置
.addTableFills(new Property("update_time", FieldFill.INSERT_UPDATE))
.enableLombok() //开启lombok
.logicDeleteColumnName("deleted")// 说明逻辑删除是哪个字段
.enableTableFieldAnnotation()// 属性加上注解说明
.controllerBuilder() //controller 策略配置
.formatFileName("%sController")
.enableRestStyle() // 开启RestController注解
.mapperBuilder()// mapper策略配置
.enableMapperAnnotation()//@mapper注解开启
.formatXmlFileName("%sMapper")
.enableBaseColumnList()
.enableBaseResultMap();
})
// 使用Freemarker引擎模板,默认的是Velocity引擎模板
// .templateEngine(new FreemarkerTemplateEngine())
.execute();
}
}
4:自定义响应体和响应码
package com.zd.resp;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Data;
import java.util.List;
@Data
//@ApiModel("返回对象")
public class ApiResult<T> {
//@ApiModelProperty(value = "是否成功")
private boolean success;
//@ApiModelProperty(value = "状态码")
private int code = 200;
//@ApiModelProperty(value = "返回数据的总数")
private Integer count;
//@ApiModelProperty(value = "描述")
private String message;
//@ApiModelProperty(value = "返回值", dataType = "T")
private T data;
public ApiResult(int code, String message) {
this.code = code;
this.message = message;
}
public ApiResult() {
}
public ApiResult(T data) {
this.data = data;
}
public ApiResult(int code, String message, T data) {
this.code = code;
this.message = message;
this.data = data;
}
public ApiResult(ResultCode code, Integer count, T data) {
this.success = code.success;
this.code = code.code;
this.message = code.message;
this.data = data;
this.count = count;
}
public ApiResult(ResultCode code, Page<T> data) {
this.success = code.success;
this.code = code.code;
this.message = code.message;
List<T> records = data.getRecords();
this.data = (T) records;
this.count = (int) data.getTotal();
}
public ApiResult(ResultCode code, T data) {
this.success = code.success;
this.code = code.code;
this.message = code.message;
this.data = data;
}
}
package com.zd.resp;
public enum ResultCode {
SUCCESS(true, 200, "操作成功!"),
// ---系统错误返回码-----
FAIL(false, 200, "操作失败"),
UNAUTHENTICATED(false, 10002, "您还未登录");
// 操作是否成功
boolean success;
// 操作代码
int code;
// 提示信息
String message;
ResultCode(boolean success, int code, String message) {
this.success = success;
this.code = code;
this.message = message;
}
public boolean success() {
return success;
}
public int code() {
return code;
}
public String message() {
return message;
}
}
5:自定义vm模板
5.1:controller.java.vm
package ${package.Controller};
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import ${package.Entity}.${entity};
import ${package.Service}.${table.serviceName};
import com.zd.resp.ResultCode;
import com.zd.resp.ApiResult;
#if(${restControllerStyle})
import org.springframework.web.bind.annotation.RestController;
#else
import org.springframework.stereotype.Controller;
#end
#if(${superControllerClassPackage})
import ${superControllerClassPackage};
#end
/**
* <p>
* $!{table.comment}
* </p>
*
* @author ${author}
* @since ${date}
*/
#if(${restControllerStyle})
@RestController
#else
@Controller
#end
@RequestMapping("/api/v1#if(${package.ModuleName})/${package.ModuleName}#end/#if(${controllerMappingHyphenStyle})${controllerMappingHyphen}#else${table.entityPath}#end")
#if(${kotlin})
class ${table.controllerName}#if(${superControllerClass}) : ${superControllerClass}()#end
#else
#if(${superControllerClass})
public class ${table.controllerName} extends ${superControllerClass} {
#else
public class ${table.controllerName} {
@Autowired
private ${table.serviceName} service;
@GetMapping
public ApiResult<${entity}> list(@RequestParam(required = false) Long current,
@RequestParam(required = false) Long size){
Page<${entity}> page = service.selectPage(current,size);
return new ApiResult<${entity}>(ResultCode.SUCCESS,page);
}
@GetMapping("/{id}")
public ApiResult<${entity}> getByid(@PathVariable("id") Long id){
${entity} entity = service.getById(id);
return new ApiResult<${entity}>(ResultCode.SUCCESS,entity);
}
@PostMapping
public ApiResult<${entity}> add(@RequestBody ${entity} data){
service.save(data);
return new ApiResult<${entity}>(ResultCode.SUCCESS,data);
}
@PutMapping("/{id}")
public ApiResult<${entity}> update(@PathVariable("id") Integer id, @RequestBody ${entity} data){
data.setId(id);
service.updateById(data);
return new ApiResult<${entity}>(ResultCode.SUCCESS,data);
}
@DeleteMapping("/{id}")
public ApiResult<${entity}> delete(@PathVariable("id") Long id){
${entity} entity = service.getById(id);
service.removeById(id);
return new ApiResult<${entity}>(ResultCode.SUCCESS,entity);
}
#end
}
#end
5.2:mapper.java.vm
package ${package.Mapper};
import ${package.Entity}.${entity};
import ${superMapperClassPackage};
import org.apache.ibatis.annotations.Mapper;
/**
* <p>
* $!{table.comment} Mapper 接口
* </p>
*
* @author ${author}
* @since ${date}
*/
#if(${kotlin})
interface ${table.mapperName} : ${superMapperClass}<${entity}>
#else
@Mapper
public interface ${table.mapperName} extends ${superMapperClass}<${entity}> {
}
#end
5.3:service.java.vm
package ${package.Service};
import ${package.Entity}.${entity};
import ${superServiceClassPackage};
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
/**
* <p>
* $!{table.comment} 服务类
* </p>
*
* @author ${author}
* @since ${date}
*/
#if(${kotlin})
interface ${table.serviceName} : ${superServiceClass}<${entity}>
#else
public interface ${table.serviceName} extends ${superServiceClass}<${entity}> {
Page<${entity}> selectPage(Long current, Long size);
}
#end
5.4:serviceImpl.java.vm
package ${package.ServiceImpl};
import ${package.Entity}.${entity};
import ${package.Mapper}.${table.mapperName};
import ${package.Service}.${table.serviceName};
import ${superServiceImplClassPackage};
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
/**
* <p>
* $!{table.comment} 服务实现类
* </p>
*
* @author ${author}
* @since ${date}
*/
@Service
#if(${kotlin})
open class ${table.serviceImplName} : ${superServiceImplClass}<${table.mapperName}, ${entity}>(), ${table.serviceName} {
}
#else
public class ${table.serviceImplName} extends ${superServiceImplClass}<${table.mapperName}, ${entity}> implements ${table.serviceName} {
@Autowired
private ${table.mapperName} mapper;
@Override
public Page<${entity}> selectPage(Long current, Long size){
Page<${entity}> page = new Page<>();
if (current != null && size != null) {
page.setCurrent(current);
page.setSize(size);
}
page.isSearchCount();
Page<${entity}> page${entity} = page(page);
return page${entity};
}
}
#end
6:生成结果
controller如下,其他不一一展示
package com.zd.controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zd.entity.Account;
import com.zd.service.AccountService;
import com.zd.resp.ResultCode;
import com.zd.resp.ApiResult;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
*
* </p>
*
* @author zd
* @since 2024-01-14
*/
@RestController
@RequestMapping("/api/v1/account")
public class AccountController {
@Autowired
private AccountService service;
@GetMapping
public ApiResult<Account> list(@RequestParam(required = false) Long current,
@RequestParam(required = false) Long size){
Page<Account> page = service.selectPage(current,size);
return new ApiResult<Account>(ResultCode.SUCCESS,page);
}
@GetMapping("/{id}")
public ApiResult<Account> getByid(@PathVariable("id") Long id){
Account entity = service.getById(id);
return new ApiResult<Account>(ResultCode.SUCCESS,entity);
}
@PostMapping
public ApiResult<Account> add(@RequestBody Account data){
service.save(data);
return new ApiResult<Account>(ResultCode.SUCCESS,data);
}
@PutMapping("/{id}")
public ApiResult<Account> update(@PathVariable("id") Integer id, @RequestBody Account data){
data.setId(id);
service.updateById(data);
return new ApiResult<Account>(ResultCode.SUCCESS,data);
}
@DeleteMapping("/{id}")
public ApiResult<Account> delete(@PathVariable("id") Long id){
Account entity = service.getById(id);
service.removeById(id);
return new ApiResult<Account>(ResultCode.SUCCESS,entity);
}
}
7:测试
package com.zd;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zd.entity.Account;
import com.zd.service.AccountService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest
class MybatisPlusGeneratorApplicationTests {
@Autowired
private AccountService service;
@Test
void test() {
Page<Account> page = service.selectPage(1l,10l);
System.out.println(page.getRecords());
System.out.println(page.getTotal());
}
}