EasyCode+MybatisPlus快速生成代码

使用EasyCode快速生成java代码并通过自定义模板进行高度自定义

https://www.bilibili.com/video/BV1YY41187fY/?spm_id_from=autoNext&vd_source=4741b9365ccc837a155892edad8f5a2c

https://blog.csdn.net/weixin_59801183/article/details/131393659

https://blog.csdn.net/yu1431/article/details/130924049

什么是EasyCode

EasyCode 是一个在 IntelliJ IDEA(一款常用的 Java 集成开发环境)中的插件,用于快速生成代码的工具。它旨在帮助开发人员提高编码效率,减少编写重复代码的工作量。

EasyCode 安装到 IntelliJ IDEA 后,可以在编辑器中自动完成代码,生成常见的代码模板和代码结构,包括类、方法、字段、注释等。它通过模板和用户输入生成代码,可以根据开发人员的需求和配置来自定义生成的代码结构。

EasyCode 提供的功能包括:

  1. 代码自动补全:根据输入的关键字,自动完成方法名、属性名等。
  2. 代码模板生成:根据用户选择的模板和配置信息,快速生成代码。
  3. 自定义代码模板:开发人员可以根据自己的需求和项目规范,自定义代码模板,使生成的代码符合要求。
  4. 代码注释:在生成的代码中,自动添加注释,提高代码的可读性和可维护性。

使用 EasyCode 插件,开发人员可以节省大量的编写重复代码的时间,快速生成基础代码结构,专注于业务逻辑的实现。

你可以在 IntelliJ IDEA 的插件市场中搜索 EasyCode,并按照指引进行安装和配置。安装完成后,你就可以在代码编辑器中享受 EasyCode 提供的便利功能了。

插件-高度自定义

根据自己习惯进行模板编写:

controller.java.vm

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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
##导入宏定义
$!{define.vm}

##设置表后缀(宏定义)
#setTableSuffix("Controller")

##保存文件(宏定义)
#save("/controller", "Controller.java")

##包路径(宏定义)
#setPackageSuffix("controller")

##定义服务名
#set($serviceName = $!tool.append($!tool.firstLowerCase($!tableInfo.name), "Service"))

##定义实体对象名
#set($entityName = $!tool.firstLowerCase($!tableInfo.name))

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import $!{tableInfo.savePackageName}.entity.$!tableInfo.name;
import $!{tableInfo.savePackageName}.service.$!{tableInfo.name}Service;
import $!{tableInfo.savePackageName}.result.Result;
import $!{tableInfo.savePackageName}.result.ResultResponse;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;

##表注释(宏定义)
#tableComment("表控制层")
@RestController
@RequestMapping("/$!tool.firstLowerCase($!tableInfo.name)")
public class $!{tableName} {
/**
* 服务对象
*/
@Resource
private $!{tableInfo.name}Service $!{serviceName};

/**
* 分页查询所有数据
*
* @param page 分页对象
* @param $!entityName 查询实体
* @return 所有数据
*/
@ApiOperation("分页查询所有数据")
@GetMapping("/selectAll")
public Result selectAll(Page<$!tableInfo.name> page, $!tableInfo.name $!entityName) {
return ResultResponse.success(this.$!{serviceName}.page(page, new QueryWrapper<>($!entityName)));
}

/**
* 通过主键查询单条数据
*
* @param id 主键
* @return 单条数据
*/
@ApiOperation("通过主键查询单条数据")
@GetMapping("{id}")
public Result selectOne(@PathVariable Serializable id) {
return ResultResponse.success(this.$!{serviceName}.getById(id));
}

/**
* 新增数据
*
* @param $!entityName 实体对象
* @return 新增结果
*/
@ApiOperation("新增数据")
@PostMapping("/insert")
public Result insert(@RequestBody $!tableInfo.name $!entityName) {
return ResultResponse.success(this.$!{serviceName}.save($!entityName));
}

/**
* 修改数据
*
* @param $!entityName 实体对象
* @return 修改结果
*/
@ApiOperation("修改数据")
@PutMapping("/update")
public Result update(@RequestBody $!tableInfo.name $!entityName) {
return ResultResponse.success(this.$!{serviceName}.updateById($!entityName));
}

/**
* 删除数据
*
* @param idList 主键结合
* @return 删除结果
*/
@ApiOperation("删除数据")
@DeleteMapping("/delete")
public Result delete(@RequestParam("idList") List<Long> idList) {
return ResultResponse.success(this.$!{serviceName}.removeByIds(idList));
}
}

service.java.vm

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
##导入宏定义
$!{define.vm}

##设置表后缀(宏定义)
#setTableSuffix("Service")

##保存文件(宏定义)
#save("/service", "Service.java")

##包路径(宏定义)
#setPackageSuffix("service")

import com.baomidou.mybatisplus.extension.service.IService;
import $!{tableInfo.savePackageName}.entity.$!tableInfo.name;

##表注释(宏定义)
#tableComment("表服务接口")
public interface $!{tableName} extends IService<$!tableInfo.name> {

}

serviceImpl.java.vm

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
##导入宏定义
$!{define.vm}

##设置表后缀(宏定义)
#setTableSuffix("ServiceImpl")

##保存文件(宏定义)
#save("/service/impl", "ServiceImpl.java")

##包路径(宏定义)
#setPackageSuffix("service.impl")

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import $!{tableInfo.savePackageName}.mapper.$!{tableInfo.name}Mapper;
import $!{tableInfo.savePackageName}.entity.$!{tableInfo.name};
import $!{tableInfo.savePackageName}.service.$!{tableInfo.name}Service;
import org.springframework.stereotype.Service;

##表注释(宏定义)
#tableComment("表服务实现类")
@Service("$!tool.firstLowerCase($tableInfo.name)Service")
public class $!{tableName} extends ServiceImpl<$!{tableInfo.name}Mapper, $!{tableInfo.name}> implements $!{tableInfo.name}Service {

}

dao.java.vm

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
##导入宏定义
$!{define.vm}

##设置表后缀(宏定义)
#setTableSuffix("Mapper")

##保存文件(宏定义)
#save("/mapper", "Mapper.java")

##包路径(宏定义)
#setPackageSuffix("mapper")

import java.util.List;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
import $!{tableInfo.savePackageName}.entity.$!tableInfo.name;

##表注释(宏定义)
#tableComment("表数据库访问层")
public interface $!{tableName} extends BaseMapper<$!tableInfo.name> {

/**
* 批量新增数据(MyBatis原生foreach方法)
*
* @param entities List<$!{tableInfo.name}> 实例对象列表
* @return 影响行数
*/
int insertBatch(@Param("entities") List<$!{tableInfo.name}> entities);

/**
* 批量新增或按主键更新数据(MyBatis原生foreach方法)
*
* @param entities List<$!{tableInfo.name}> 实例对象列表
* @return 影响行数
* @throws org.springframework.jdbc.BadSqlGrammarException 入参是空List的时候会抛SQL语句错误的异常,请自行校验入参
*/
int insertOrUpdateBatch(@Param("entities") List<$!{tableInfo.name}> entities);

}

mapper.xml.vm

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
##引入mybatis支持
$!{mybatisSupport.vm}

##设置保存名称与保存位置
$!callback.setFileName($tool.append($!{tableInfo.name}, "Mapper.xml"))
$!callback.setSavePath($tool.append($modulePath, "/src/main/resources/mapper"))

##拿到主键
#if(!$tableInfo.pkColumn.isEmpty())
#set($pk = $tableInfo.pkColumn.get(0))
#end

<?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="$!{tableInfo.savePackageName}.mapper.$!{tableInfo.name}Mapper">

<resultMap type="$!{tableInfo.savePackageName}.entity.$!{tableInfo.name}" id="$!{tableInfo.name}Map">
#foreach($column in $tableInfo.fullColumn)
<result property="$!column.name" column="$!column.obj.name" jdbcType="$!column.ext.jdbcType"/>
#end
</resultMap>

<!-- 批量插入 -->
<insert id="insertBatch" keyProperty="$!pk.name" useGeneratedKeys="true">
insert into $!{tableInfo.obj.parent.name}.$!{tableInfo.obj.name}(#foreach($column in $tableInfo.otherColumn)$!column.obj.name#if($velocityHasNext), #end#end)
values
<foreach collection="entities" item="entity" separator=",">
(#foreach($column in $tableInfo.otherColumn)#{entity.$!{column.name}}#if($velocityHasNext), #end#end)
</foreach>
</insert>
<!-- 批量插入或按主键更新 -->
<insert id="insertOrUpdateBatch" keyProperty="$!pk.name" useGeneratedKeys="true">
insert into $!{tableInfo.obj.parent.name}.$!{tableInfo.obj.name}(#foreach($column in $tableInfo.otherColumn)$!column.obj.name#if($velocityHasNext), #end#end)
values
<foreach collection="entities" item="entity" separator=",">
(#foreach($column in $tableInfo.otherColumn)#{entity.$!{column.name}}#if($velocityHasNext), #end#end)
</foreach>
on duplicate key update
#foreach($column in $tableInfo.otherColumn)$!column.obj.name = values($!column.obj.name) #if($velocityHasNext), #end#end
</insert>

</mapper>

entity.java.vm

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
##导入宏定义
$!{define.vm}

##保存文件(宏定义)
#save("/entity", ".java")

##包路径(宏定义)
#setPackageSuffix("entity")

##自动导入包(全局变量)
$!autoImport
import java.io.Serializable;
import io.swagger.annotations.ApiModel;
import lombok.Data;
import java.util.Date;

##表注释(宏定义)
#tableComment("表实体类")
@Data
public class $!{tableInfo.name} implements Serializable {

#foreach($column in $tableInfo.fullColumn)
#if(${column.comment})
@ApiModelProperty(value = "${column.comment}")
#end
private $!{tool.getClsNameByFullName($column.type)} $!{column.name};

#end

}

MybatisPlusConfig.java.vm

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
##导入宏定义
$!{define.vm}

##保存文件(宏定义)
#save("/config")

##设置保存名称与保存位置
$!callback.setFileName("MybatisPlusConfig.java")

##包路径(宏定义)
#setPackageSuffix("config")

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@MapperScan({"$!{tableInfo.savePackageName}.mapper"})
public class MybatisPlusConfig {

//分页插件注册
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(){
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return interceptor;
}

}

MyMetaObjectHandler.java.vm

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
##导入宏定义
$!{define.vm}

##保存文件(宏定义)
#save("/config")

##设置保存名称与保存位置
$!callback.setFileName("MyMetaObjectHandler.java")

##包路径(宏定义)
#setPackageSuffix("config")

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
* 让MybatisPlus中的自动生成时间生效
*/
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

@Override
public void insertFill(MetaObject metaObject) {
this.setFieldValByName("createTime", LocalDateTime.now(),metaObject);
this.setFieldValByName("updateTime", LocalDateTime.now(),metaObject);
}

@Override
public void updateFill(MetaObject metaObject) {
this.setFieldValByName("updateTime", LocalDateTime.now(),metaObject);
}
}

Result.java.vm

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
##导入宏定义
$!{define.vm}

##保存文件(宏定义)
#save("/result")

##设置保存名称与保存位置
$!callback.setFileName("Result.java")

##包路径(宏定义)
#setPackageSuffix("result")

import lombok.Data;

import java.io.Serializable;

/**
* 统一API响应结果格式封装
*/
@Data
public class Result<T> implements Serializable {

private static final long serialVersionUID = 6308315887056661996L;
private Integer code;
private String message;
private T data;


public Result setResult(ResultCode resultCode) {
this.code = resultCode.getCode();
this.message = resultCode.getMessage();
return this;
}

public Result setResult(ResultCode resultCode, T data) {
this.code = resultCode.getCode();
this.message = resultCode.getMessage();
this.setData(data);
return this;
}
}

ResultCode.java.vm

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
##导入宏定义
$!{define.vm}

##保存文件(宏定义)
#save("/result")

##设置保存名称与保存位置
$!callback.setFileName("ResultCode.java")

##包路径(宏定义)
#setPackageSuffix("result")

import lombok.Getter;

/**
* 响应码枚举,对应HTTP状态码
*/
@Getter
public enum ResultCode {

SUCCESS(200, "成功"),//成功
BAD_REQUEST(400, "失败"),
UNAUTHORIZED(401, "认证失败"),//未认证
NOT_FOUND(404, "接口不存在"),//接口不存在
INTERNAL_SERVER_ERROR(500, "服务器内部错误"),//服务器内部错误
METHOD_NOT_ALLOWED(405,"方法不被允许"),
ILLEGAL_HEADER(406,"请求头无效"),
REPLAY_ERROR(410,"请求重复"),
/*参数错误:1001-1999*/
PARAMS_IS_INVALID(1001, "参数无效"),
PARAMS_IS_BLANK(1002, "参数为空");
/*用户错误2001-2999*/

private Integer code;
private String message;

ResultCode(int code, String message) {
this.code = code;
this.message = message;
}
}

ResultResponse.java.vm

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
##导入宏定义
$!{define.vm}

##保存文件(宏定义)
#save("/result")

##设置保存名称与保存位置
$!callback.setFileName("ResultResponse.java")

##包路径(宏定义)
#setPackageSuffix("result")

/**
* 响应结果封装
*/
public class ResultResponse {


// 只返回状态
public static Result success() {
return new Result()
.setResult(ResultCode.SUCCESS);
}

// 成功返回数据
public static Result success(Object data) {
return new Result()
.setResult(ResultCode.SUCCESS, data);


}

// 失败
public static Result failure(ResultCode resultCode) {
return new Result()
.setResult(resultCode);
}

// 失败
public static Result failure(ResultCode resultCode, Object data) {
return new Result()
.setResult(resultCode, data);
}

//参数无效
public static Result paramInvalid(Object data) {
return new Result()
.setResult(ResultCode.PARAMS_IS_INVALID, data);
}


}

数据库环境搭建

此处准备了两张表:

项目初始化

项目创建

创建项目

选择SpringBoot2,不选择依赖

删除没必要的文件:

配置依赖和yml配置文件

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
<!--Web供Controller使用-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.30</version>
</dependency>

<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>

<!--mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3</version>
</dependency>

<!-- 代码生成器依赖-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.3.0</version>
</dependency>

<!--模板引擎 依赖:mybatis-plus代码生成的时候报异常-->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.0</version>
</dependency>
<!--配置ApiModel在实体类中不生效-->
<dependency>
<groupId>com.spring4all</groupId>
<artifactId>spring-boot-starter-swagger</artifactId>
<version>1.5.1.RELEASE</version>
</dependency>
<!--freemarker(模板引擎)-->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.30</version>
</dependency>
<!-- 时间格式化需要-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>4.6.17</version>
</dependency>
<!--beet(Java模板引擎))-->
<dependency>
<groupId>com.ibeetl</groupId>
<artifactId>beetl</artifactId>
<version>3.3.2.RELEASE</version>
</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-extension</artifactId>
<version>3.5.2</version>
</dependency>

1
2
3
4
5
6
7
8
9
10
11
12
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
username: root
password: 123456

# 配置mybatisPlus日志
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

IDEA连接数据库

通过EasyCode生成代码

选择包名:

代码生成与文件展示

controller

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
86
87
88
89
90
91
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.why.entity.Poet;
import com.why.service.PoetService;
import com.why.result.Result;
import com.why.result.ResultResponse;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;

/**
* (Poet)表控制层
*
* @author wahoyu
* @since 2023-08-15 14:55:12
*/
@RestController
@RequestMapping("/poet")
public class PoetController {
/**
* 服务对象
*/
@Resource
private PoetService poetService;

/**
* 分页查询所有数据
*
* @param page 分页对象
* @param poet 查询实体
* @return 所有数据
*/
@ApiOperation("分页查询所有数据")
@GetMapping("/selectAll")
public Result selectAll(Page<Poet> page, Poet poet) {
return ResultResponse.success(this.poetService.page(page, new QueryWrapper<>(poet)));
}

/**
* 通过主键查询单条数据
*
* @param id 主键
* @return 单条数据
*/
@ApiOperation("通过主键查询单条数据")
@GetMapping("{id}")
public Result selectOne(@PathVariable Serializable id) {
return ResultResponse.success(this.poetService.getById(id));
}

/**
* 新增数据
*
* @param poet 实体对象
* @return 新增结果
*/
@ApiOperation("新增数据")
@PostMapping("/insert")
public Result insert(@RequestBody Poet poet) {
return ResultResponse.success(this.poetService.save(poet));
}

/**
* 修改数据
*
* @param poet 实体对象
* @return 修改结果
*/
@ApiOperation("修改数据")
@PutMapping("/update")
public Result update(@RequestBody Poet poet) {
return ResultResponse.success(this.poetService.updateById(poet));
}

/**
* 删除数据
*
* @param idList 主键结合
* @return 删除结果
*/
@ApiOperation("删除数据")
@DeleteMapping("/delete")
public Result delete(@RequestParam("idList") List<Long> idList) {
return ResultResponse.success(this.poetService.removeByIds(idList));
}
}

service

1
2
3
4
5
6
7
8
9
10
11
12
13
import com.baomidou.mybatisplus.extension.service.IService;
import com.why.entity.Poet;

/**
* (Poet)表服务接口
*
* @author wahoyu
* @since 2023-08-15 14:55:12
*/
public interface PoetService extends IService<Poet> {

}

serviceImpl

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.why.mapper.PoetMapper;
import com.why.entity.Poet;
import com.why.service.PoetService;
import org.springframework.stereotype.Service;

/**
* (Poet)表服务实现类
*
* @author wahoyu
* @since 2023-08-15 14:55:12
*/
@Service("poetService")
public class PoetServiceImpl extends ServiceImpl<PoetMapper, Poet> implements PoetService {

}

dao(mapper)

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
import java.util.List;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
import com.why.entity.Poet;

/**
* (Poet)表数据库访问层
*
* @author wahoyu
* @since 2023-08-15 14:55:12
*/
public interface PoetMapper extends BaseMapper<Poet> {

/**
* 批量新增数据(MyBatis原生foreach方法)
*
* @param entities List<Poet> 实例对象列表
* @return 影响行数
*/
int insertBatch(@Param("entities") List<Poet> entities);

/**
* 批量新增或按主键更新数据(MyBatis原生foreach方法)
*
* @param entities List<Poet> 实例对象列表
* @return 影响行数
* @throws org.springframework.jdbc.BadSqlGrammarException 入参是空List的时候会抛SQL语句错误的异常,请自行校验入参
*/
int insertOrUpdateBatch(@Param("entities") List<Poet> entities);

}

mapper.xml

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
<?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.why.mapper.PoetMapper">

<resultMap type="com.why.entity.Poet" id="PoetMap">
<result property="id" column="id" jdbcType="INTEGER"/>
<result property="username" column="username" jdbcType="VARCHAR"/>
<result property="email" column="email" jdbcType="VARCHAR"/>
<result property="sex" column="sex" jdbcType="VARCHAR"/>
<result property="city" column="city" jdbcType="VARCHAR"/>
<result property="sign" column="sign" jdbcType="VARCHAR"/>
</resultMap>

<!-- 批量插入 -->
<insert id="insertBatch" keyProperty="id" useGeneratedKeys="true">
insert into test.poet(username, email, sex, city, sign)
values
<foreach collection="entities" item="entity" separator=",">
(#{entity.username}, #{entity.email}, #{entity.sex}, #{entity.city}, #{entity.sign})
</foreach>
</insert>
<!-- 批量插入或按主键更新 -->
<insert id="insertOrUpdateBatch" keyProperty="id" useGeneratedKeys="true">
insert into test.poet(username, email, sex, city, sign)
values
<foreach collection="entities" item="entity" separator=",">
(#{entity.username}, #{entity.email}, #{entity.sex}, #{entity.city}, #{entity.sign})
</foreach>
on duplicate key update
username = values(username) , email = values(email) , sex = values(sex) , city = values(city) , sign = values(sign) </insert>

</mapper>

entity

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
import java.io.Serializable;
import io.swagger.annotations.ApiModel;
import lombok.Data;
import java.util.Date;

/**
* (Poet)表实体类
*
* @author wahoyu
* @since 2023-08-15 14:59:55
*/
@Data
public class Poet implements Serializable {

private Integer id;

private String username;

private String email;

private String sex;

private String city;

private String sign;

}

MybatisPlusConfig

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@MapperScan({"com.why.mapper"})
public class MybatisPlusConfig {

//分页插件注册
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(){
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return interceptor;
}

}

MyMetaObjectHandler

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
* 让MybatisPlus中的自动生成时间生效
*/
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

@Override
public void insertFill(MetaObject metaObject) {
this.setFieldValByName("createTime", LocalDateTime.now(),metaObject);
this.setFieldValByName("updateTime", LocalDateTime.now(),metaObject);
}

@Override
public void updateFill(MetaObject metaObject) {
this.setFieldValByName("updateTime", LocalDateTime.now(),metaObject);
}
}

Result

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
import lombok.Data;
import java.io.Serializable;

/**
* 统一API响应结果格式封装
*/
@Data
public class Result<T> implements Serializable {

private static final long serialVersionUID = 6308315887056661996L;
private Integer code;
private String message;
private T data;


public Result setResult(ResultCode resultCode) {
this.code = resultCode.getCode();
this.message = resultCode.getMessage();
return this;
}

public Result setResult(ResultCode resultCode, T data) {
this.code = resultCode.getCode();
this.message = resultCode.getMessage();
this.setData(data);
return this;
}
}

ResultCode

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
import lombok.Getter;

/**
* 响应码枚举,对应HTTP状态码
*/
@Getter
public enum ResultCode {

SUCCESS(200, "成功"),//成功
BAD_REQUEST(400, "失败"),
UNAUTHORIZED(401, "认证失败"),//未认证
NOT_FOUND(404, "接口不存在"),//接口不存在
INTERNAL_SERVER_ERROR(500, "服务器内部错误"),//服务器内部错误
METHOD_NOT_ALLOWED(405,"方法不被允许"),
ILLEGAL_HEADER(406,"请求头无效"),
REPLAY_ERROR(410,"请求重复"),
/*参数错误:1001-1999*/
PARAMS_IS_INVALID(1001, "参数无效"),
PARAMS_IS_BLANK(1002, "参数为空");
/*用户错误2001-2999*/

private Integer code;
private String message;

ResultCode(int code, String message) {
this.code = code;
this.message = message;
}
}

ResultResponse

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
/**
* 响应结果封装
*/
public class ResultResponse {


// 只返回状态
public static Result success() {
return new Result()
.setResult(ResultCode.SUCCESS);
}

// 成功返回数据
public static Result success(Object data) {
return new Result()
.setResult(ResultCode.SUCCESS, data);


}

// 失败
public static Result failure(ResultCode resultCode) {
return new Result()
.setResult(resultCode);
}

// 失败
public static Result failure(ResultCode resultCode, Object data) {
return new Result()
.setResult(resultCode, data);
}

//参数无效
public static Result paramInvalid(Object data) {
return new Result()
.setResult(ResultCode.PARAMS_IS_INVALID, data);
}
}

运行测试


EasyCode+MybatisPlus快速生成代码
http://wahoyu.xyz/2023/08/15/EasyCode+MybatisPlus快速生成代码/
作者
Wahoyu
发布于
2023年8月15日
许可协议