使用mybatis-plus-generator配置一套适合你的CRUD
1、maven引入 mybatis-plus-generator 和模板引擎,你也可以使用freemarker之类的,看个人
<!-- mybatisplus代码生成器 --><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-generator</artifactId><version>3.5.1</version></dependency><!-- velocity模板引擎 --><dependency><groupId>org.apache.velocity</groupId><artifactId>velocity-engine-core</artifactId><version>2.0</version></dependency>
2、创建MybatisCrud工具类,这里可以做很多个性化配置,比如改名他默认的 IService之类的,指定表,忽略某些字段等。更多详情见官网 代码生成器配置新 | MyBatis-Plus
package com.XXXX.utils;import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.XXXX.entity.BaseEntity;import java.util.Collections;/*** @Auther:Tiancong Zou* @Date: 2023/3/16 21:46* @Description:*/
public class MybatisCrud {public static void main(String[] args) {FastAutoGenerator.create("jdbc:mysql://127.0.0.1:3306/数据库名" ,"root" ,"").globalConfig(builder -> {builder.author("Tiancong Zou") // 设置作者.enableSwagger() // 开启 swagger 模式.fileOverride() // 覆盖已生成文件.outputDir("D:\\myJavaTest\\"); // 指定输出目录}).packageConfig(builder -> {builder.parent("com.XXXX") // 设置父包名.mapper("dao").pathInfo(Collections.singletonMap(OutputFile.mapperXml, "D:\\myJavaTest\\mapper\\")); // 设置mapperXml生成路径}).strategyConfig(builder -> {builder.serviceBuilder().formatServiceFileName("%sService").formatServiceImplFileName("%sServiceImpl").convertServiceFileName((entityName -> entityName + "Service"));builder.addInclude("sys_dict_item");// 设置需要生成的表名builder.entityBuilder().superClass(BaseEntity.class ).addIgnoreColumns("deleted","create_date","update_date");}).execute();}
}
3、copy模板,进行定制配置,找到jar包下的模板,复制templates到resources文件夹下,删除其他你不需要的模板。
4、模板配置,这边使用 velocity 模板做演示
4.1 controller.java.vm
package ${package.Controller};import org.springframework.web.bind.annotation.*;
import ${package.Service}.${table.serviceName};
import ${package.Entity}.${entity};
import com.muchuantong.utils.Result;
import com.muchuantong.utils.SnowFlake;
import org.springframework.beans.factory.annotation.Autowired;import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Map;#if(${superControllerClassPackage})
import ${superControllerClassPackage};
#end/*** <p>* $!{table.comment} 前端控制器* </p>** @Author: ${author}* @Date: ${date}* @Annotation:*/@RestController
@RequestMapping("#if(${package.ModuleName})/${package.ModuleName}#end/#if(${controllerMappingHyphenStyle})${controllerMappingHyphen}#else${table.entityPath}#end")
public class ${table.controllerName} {@Autowired
private ${table.serviceName} ${table.entityPath}Service;// 分页
@GetMapping("getPage")
public Result<Object> page(@ModelAttribute DTO dto){return ${table.entityPath}Service.getPage(dto);}// 新增
@PostMapping("save")
public Result<Object> save(@RequestBody ${entity} ${table.entityPath}){${table.entityPath}.setId(Long.toString(SnowFlake.nextId()));${table.entityPath}.setCreateDate(new Timestamp(new Date().getTime()));${table.entityPath}.setUpdateDate(new Timestamp(new Date().getTime()));try{${table.entityPath}Service.save(${table.entityPath});return new Result<>();}catch(Exception e){e.printStackTrace();return new Result<>("201" ,"未知错误");}}
// 修改
@PostMapping("update")
public Result<Object> update(@RequestBody ${entity} ${table.entityPath}){try{${table.entityPath}.setUpdateDate(new Timestamp(new Date().getTime()));${table.entityPath}Service.updateById(${table.entityPath});return new Result<>();}catch(Exception e){e.printStackTrace();return new Result<>("201" ,"未知错误");}}// 根据id获取
@GetMapping("getById/{id}")
public Result<Object> getById(@PathVariable("id") Long id){${entity} ${table.entityPath} = ${table.entityPath}Service.getById(id);return new Result<>(${table.entityPath});}// 逻辑删除
@PostMapping("deleteByIds")
public Result<Object> deleteByIds(@RequestBody List<Long> ids){for (Long id : ids) {${entity} ${table.entityPath} = ${table.entityPath}Service.getById(id);${table.entityPath}.setDeleted(1);try {${table.entityPath}Service.updateById(${table.entityPath});return new Result<>();} catch (Exception e) {e.printStackTrace();return new Result<>("201", "未知错误");}}return null;}}
4.2 service.java.vm
package ${package.Service};import ${package.Entity}.${entity};
import ${superServiceClassPackage};
import com.muchuantong.utils.Result;import java.util.Map;/*** <p>* $!{table.comment} 服务类* </p>** @Author: ${author}* @Date: ${date}* @Annotation:*/
public interface ${table.serviceName} extends ${superServiceClass}<${entity}> {Result getPage(DTO dto);}
4.3 serviceImpl.java.vm
package ${package.ServiceImpl};
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.primitives.Longs;
import ${package.Entity}.${entity};
import ${package.Mapper}.${table.mapperName};
import ${package.Service}.${table.serviceName};
import ${superServiceImplClassPackage};
import com.muchuantong.utils.Result;
import org.springframework.stereotype.Service;import java.util.Map;
import java.util.Optional;
/*** <p>* $!{table.comment} 服务实现类* </p>** @Author: ${author}* @Date: ${date}* @Annotation:*/
@Service
public class ${table.serviceImplName} extends ${superServiceImplClass}<${table.mapperName}, ${entity}> implements ${table.serviceName} {
@Override
public Result getPage(DTO dto){QueryWrapper<${entity}> wrapper=new QueryWrapper<>();Page<${entity}> page=page(new Page<>(dto.getCurrent(),dto.getSize()),wrapper);return new Result<> (page);}}
4.4 entity.java.vm
package ${package.Entity};#foreach($pkg in ${table.importPackages})
import ${pkg};
#end
#if(${swagger})
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
#end
#if(${entityLombokModel})
import lombok.Getter;
import lombok.Setter;#if(${chainModel})import lombok.experimental.Accessors;#end
#end/*** <p>* $!{table.comment}* </p>** @author ${author}* @since ${date}*/
#if(${entityLombokModel})
@Getter
@Setter#if(${chainModel})@Accessors(chain = true)#end
#end
#if(${table.convert})
@TableName("${schemaName}${table.name}")
#end
#if(${swagger})
@ApiModel(value = "${entity}对象", description = "$!{table.comment}")
#end
#if(${superEntityClass})
public class ${entity} extends ${superEntityClass}#if(${activeRecord})<${entity}>#end {
#elseif(${activeRecord})
public class ${entity} extends Model<${entity}> {
#elseif(${entitySerialVersionUID})
public class ${entity} implements Serializable {
#else
public class ${entity}{
#end
#if(${entitySerialVersionUID})private static final long serialVersionUID = 1L;
#end
## ---------- BEGIN 字段循环遍历 ----------
#foreach($field in ${table.fields})#if(${field.keyFlag})#set($keyPropertyName=${field.propertyName})#end#if("$!field.comment" != "")#if(${swagger})@ApiModelProperty("${field.comment}")#else/*** ${field.comment}*/#end#end#if(${field.keyFlag})## 主键#if(${field.keyIdentityFlag})@TableId(value = "${field.annotationColumnName}", type = IdType.AUTO)#elseif(!$null.isNull(${idType}) && "$!idType" != "")@TableId(value = "${field.annotationColumnName}", type = IdType.${idType})#elseif(${field.convert})@TableId("${field.annotationColumnName}")#end## 普通字段#elseif(${field.fill})## ----- 存在字段填充设置 -----#if(${field.convert})@TableField(value = "${field.annotationColumnName}", fill = FieldFill.${field.fill})#else@TableField(fill = FieldFill.${field.fill})#end#elseif(${field.convert})@TableField("${field.annotationColumnName}")#end## 乐观锁注解#if(${field.versionField})@Version#end## 逻辑删除注解#if(${field.logicDeleteField})@TableLogic#end
private ${field.propertyType} ${field.propertyName};
#end
## ---------- END 字段循环遍历 ----------#if(!${entityLombokModel})#foreach($field in ${table.fields})#if(${field.propertyType.equals("boolean")})#set($getprefix="is")#else#set($getprefix="get")#endpublic ${field.propertyType} ${getprefix}${field.capitalName}() {return ${field.propertyName};}#if(${chainModel})public ${entity} set${field.capitalName}(${field.propertyType} ${field.propertyName}) {#elsepublic void set${field.capitalName}(${field.propertyType} ${field.propertyName}) {#endthis.${field.propertyName} = ${field.propertyName};#if(${chainModel})return this;#end}#end## --foreach end---
#end
## --end of #if(!${entityLombokModel})--#if(${entityColumnConstant})#foreach($field in ${table.fields})public static final String ${field.name.toUpperCase()} = "${field.name}";#end
#end
#if(${activeRecord})
@Override
public Serializable pkVal() {#if(${keyPropertyName})return this.${keyPropertyName};#elsereturn null;#end}#end
#if(!${entityLombokModel})
@Override
public String toString() {return "${entity}{" +#foreach($field in ${table.fields})#if($!{foreach.index}==0)"${field.propertyName}=" + ${field.propertyName} +#else", ${field.propertyName}=" + ${field.propertyName} +#end#end"}";}
#end}
4.5 mapper.java.vm
package ${package.Mapper};import ${package.Entity}.${entity};
import ${superMapperClassPackage};
#if(${mapperAnnotation})
import org.apache.ibatis.annotations.Mapper;
#end/*** <p>* $!{table.comment} Mapper 接口* </p>** @Author: ${author}* @Date: ${date}* @Annotation:*/
#if(${mapperAnnotation})
@Mapper
#end
#if(${kotlin})
interface ${table.mapperName} : ${superMapperClass}<${entity}>
#else
public interface ${table.mapperName} extends ${superMapperClass}<${entity}> {}
#end
4.6 mapper.xml.vm
<?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="${package.Mapper}.${table.mapperName}"><!-- 通用查询映射结果 --><resultMap id="BaseResultMap" type="${package.Entity}.${entity}">#foreach($field in ${table.fields})#if(${field.keyFlag})##生成主键排在第一位<id column="${field.name}" property="${field.propertyName}" />#end#end#foreach($field in ${table.commonFields})##生成公共字段<result column="${field.name}" property="${field.propertyName}" />#end#foreach($field in ${table.fields})#if(!${field.keyFlag})##生成普通字段<result column="${field.name}" property="${field.propertyName}" />#end#end</resultMap><!-- 通用查询结果列 --><sql id="Base_Column_List">#foreach($field in ${table.commonFields})${field.columnName},#end${table.fieldNames}</sql>
</mapper>
5、生成代码预览,毫无问题 controller
package com.muchuantong.controller;import com.muchuantong.entity.DTO;
import org.springframework.web.bind.annotation.*;
import com.muchuantong.service.SysDictItemService;
import com.muchuantong.entity.SysDictItem;
import com.muchuantong.utils.Result;
import com.muchuantong.utils.SnowFlake;
import org.springframework.beans.factory.annotation.Autowired;import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Map;/*** <p>* 前端控制器* </p>** @Author: Tiancong Zou* @Date: 2023-03-28* @Annotation:*/@RestController
@RequestMapping("/sysDictItem")
public class SysDictItemController {@Autowiredprivate SysDictItemService sysDictItemService;// 分页@GetMapping("getPage")public Result<Object> page(@ModelAttribute DTO dto){return sysDictItemService.getPage(dto);}// 新增@PostMapping("save")public Result<Object> save(@RequestBody SysDictItem sysDictItem){sysDictItem.setId(Long.toString(SnowFlake.nextId()));sysDictItem.setCreateDate(new Timestamp(new Date().getTime()));sysDictItem.setUpdateDate(new Timestamp(new Date().getTime()));try{sysDictItemService.save(sysDictItem);return new Result<>();}catch(Exception e){e.printStackTrace();return new Result<>("201" ,"未知错误");}}// 修改@PostMapping("update")public Result<Object> update(@RequestBody SysDictItem sysDictItem){try{sysDictItem.setUpdateDate(new Timestamp(new Date().getTime()));sysDictItemService.updateById(sysDictItem);return new Result<>();}catch(Exception e){e.printStackTrace();return new Result<>("201" ,"未知错误");}}// 根据id获取@GetMapping("getById/{id}")public Result<Object> getById(@PathVariable("id") Long id){SysDictItem sysDictItem = sysDictItemService.getById(id);return new Result<>(sysDictItem);}// 逻辑删除@PostMapping("deleteByIds")public Result<Object> deleteByIds(@RequestBody List<Long> ids){for (Long id : ids) {SysDictItem sysDictItem = sysDictItemService.getById(id);sysDictItem.setDeleted(1);try {sysDictItemService.updateById(sysDictItem);return new Result<>();} catch (Exception e) {e.printStackTrace();return new Result<>("201", "未知错误");}}return null;}
}
相关文章:

使用mybatis-plus-generator配置一套适合你的CRUD
1、maven引入 mybatis-plus-generator 和模板引擎,你也可以使用freemarker之类的,看个人 <!-- mybatisplus代码生成器 --><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-generator</artifactI…...
MATLAB实现各种离散概率密度函数(概率密度/分布/逆概率分布函数)
MATLAB实现各种离散概率密度函数(概率密度/分布/逆概率分布函数) 1 常见离散概率分布的基本信息2 常见离散概率分布计算及MATLAB实现2.1 二项分布(Binomial Distribution)2.1.1 常用函数2.2 负二项分布(Negative Binomial Distribution)2.2.1 常用函数2.3 几何分布(Geom…...
指针的基本知识
我们不会用bit去表达一个数据,因为只能放0和1,能表达的数据太少了,内存地址最小单位是字节 11111111 0x0011 1字节8bit,8bit才算作一个地址,地址是以字节为最小单位&#…...

当你的IDE装上GPT
文章目录前言下载安装使用步骤前言 我们可能要从“CV”工程师变成“KL工程师了,为什么叫”KL“工程师呢, 因为只要K和L两个指令就可以直接生成代码、修改代码,哪行代码不会点哪里,他都给你解释得明明白白。 提示:以下…...

一图看懂 pathlib 模块:面向对象的文件系统路径, 资料整理+笔记(大全)
本文由 大侠(AhcaoZhu)原创,转载请声明。 链接: https://blog.csdn.net/Ahcao2008 一图看懂 pathlib 模块:面向对象的文件系统路径, 资料整理笔记(大全)摘要模块图类关系图模块全展开【pathlib】统计常量intbooltuple模块9 fnmatc…...

前端如何将node.js 和mongodb部署到linux服务器上
本文首发自掘金。 记录了我第一次成功部署node.js 和mongodb到linux服务器上了,期间也遇到一些小坑,但是网上各位大佬记录的文章帮了大忙,所以我也将过程记录了下来。 安装Node 使用nvm linux上安装node,肯定首选nvmÿ…...
mysql数据迁移
背景:随着时间的推移,交易系统中的订单表越来越大,目前达到500w数据。为了防止数据量过大导致的查询性能问题,现将订单表进行拆分,分为实时库和历史库。实时库保留近6个月的数据,用于退款业务需求ÿ…...
【4.3蓝桥备战】小朋友崇拜圈、正则问题
文章目录小朋友崇拜圈正则问题小朋友崇拜圈 小朋友崇拜圈 - 蓝桥云课 (lanqiao.cn) 拿到这道题要先把题目读懂。 下面的一行是表示:编号为i的小朋友,崇拜的对象为编号为path[i]的小朋友。 本题应该使用DFS,深度优先遍历找到可以成环的崇拜圈…...
MySQL读写分离中间件
1.什么是读写分离中间件? 就是实现当[写]的时候转发到主库,当[读]的时候转发到从库的工具。 很类似学习过的proxy,比如nginx proxy做动静分离. 2.为什么要实现读写分离? 1)让主库专注于写,因为读可以有很多从库可以干…...

【Spring源码设计模式】单例模式外带设计模式的单例模式
Bean的概念 是Spring框架在运行时管理的对象,是任何引用程序的基本构建块。 Bean的属性 id属性:Bean的唯一标志名,必须以字母开头且不包含特殊字符 class属性:用来定义类的全限定名(包名 类名) name属性…...

go并发编程 —— singleflight设计模式
什么是singleflight singleflight是一种并发编程设计模式,将同一时刻的多个并发请求合并成一个请求,以减少对下游服务的压力 为什么叫singleflight fly可以理解为请求数,singleflight就是单个请求 使用场景 该模式主要用于防止缓存击穿 …...

【LeetCode】二叉树的中序遍历(递归,迭代,Morris遍历)
目录 题目要求:给定一个二叉树的根节点 root ,返回 它的 中序 遍历 。 方法一:递归 方法二:迭代 思路分析: 复杂度分析 代码展示: 方法三:Morris 遍历 思路分析: 复杂度分析…...

银行数字化转型导师坚鹏:数字化转型背景下的银行柜员提升之道
数字化转型背景下的银行柜员提升之道 课程背景: 很多银行都在开展银行数字化运营工作,目前存在以下问题急需解决: l 不清楚银行数字化运营包括哪些关键工作? l 不清楚银行数字化运营工作的核心方法论? l 不清楚银行数字…...

ChatGPT的平替来了?一文总结 ChatGPT 的开源平替,你值得拥有
文章目录【AIGC精选】总结 ChatGPT 的开源平替,你值得拥有1.斯坦福发布 Alpaca 7B,性能匹敌 GPT-3.52.弥补斯坦福 Alpaca 中文短板,中文大模型 BELLE 开源3.国产AI大模型 ChatGLM-6B 开启内测4.中文 Alpaca 模型 Luotuo 开源5. ChatGPT 最强竞…...

关于数据同步工具DataX部署
1.DataX简介 1.1 DataX概述 DataX 是阿里巴巴开源的一个异构数据源离线同步工具,致力于实现包括关系型数据库(MySQL、Oracle等)、HDFS、Hive、ODPS、HBase、FTP等各种异构数据源之间稳定高效的数据同步功能。 源码地址:GitHub - alibaba/DataX: DataX是…...
如何开发JetBrains插件
1 标题安装 IntelliJ IDEA 如果您还没有安装 IntelliJ IDEA,从官方网站下载并安装 IntelliJ IDEA Community Edition(免费)或 Ultimate Edition(付费)。 2 创建插件项目 在 IntelliJ IDEA 中,创建一个新…...

企业采购成本管理的难题及解决方案
企业采购成本控制是企业管理中的一个重要方面,也是一个不容易解决的难题。企业采购成本控制面临的难题包括以下几个方面: 1、采购流程复杂 企业采购通常需要经过一系列的流程,包括采购计划、采购申请、报价、比价、议标、合同签订、验收、付…...
龙蜥白皮书精选:基于 SM4 算法的文件加密(fscrypt)实践
文/张天佳 通常我们会以文件作为数据载体,使用磁盘,USB 闪存,SD 卡等存储介质进行数据存储,即便数据已经离线存储,仍然不能保证该存储介质不会丢失,如果丢失那么对于我们来说有可能是灾难性的事件。因此对…...

【SpringBoot入门】SpringBoot的配置
SpringBoot的配置文件一、SpringBoot配置文件分类二、yaml 概述三、多环境配置四、Value 和 ConfigurationProperties五、总结一、SpringBoot配置文件分类 SpringBoot 是基于约定的,很多配置都是默认的(主方法上SpringBootApplication注解的子注解Enabl…...
react 学习整理
如何使用引号传递字符串 常见的 <imgclassName avatersrc http://...alt gregorio y />或者声明变量来保存 export default function XXX(){ const avator avator const description gergorio y return (<image className XXXsrc {avator}alt {alt} />)…...
今日科技热点速览
🔥 今日科技热点速览 🎮 任天堂Switch 2 正式发售 任天堂新一代游戏主机 Switch 2 今日正式上线发售,主打更强图形性能与沉浸式体验,支持多模态交互,受到全球玩家热捧 。 🤖 人工智能持续突破 DeepSeek-R1&…...

mysql已经安装,但是通过rpm -q 没有找mysql相关的已安装包
文章目录 现象:mysql已经安装,但是通过rpm -q 没有找mysql相关的已安装包遇到 rpm 命令找不到已经安装的 MySQL 包时,可能是因为以下几个原因:1.MySQL 不是通过 RPM 包安装的2.RPM 数据库损坏3.使用了不同的包名或路径4.使用其他包…...
【Java学习笔记】BigInteger 和 BigDecimal 类
BigInteger 和 BigDecimal 类 二者共有的常见方法 方法功能add加subtract减multiply乘divide除 注意点:传参类型必须是类对象 一、BigInteger 1. 作用:适合保存比较大的整型数 2. 使用说明 创建BigInteger对象 传入字符串 3. 代码示例 import j…...

推荐 github 项目:GeminiImageApp(图片生成方向,可以做一定的素材)
推荐 github 项目:GeminiImageApp(图片生成方向,可以做一定的素材) 这个项目能干嘛? 使用 gemini 2.0 的 api 和 google 其他的 api 来做衍生处理 简化和优化了文生图和图生图的行为(我的最主要) 并且有一些目标检测和切割(我用不到) 视频和 imagefx 因为没 a…...
绕过 Xcode?使用 Appuploader和主流工具实现 iOS 上架自动化
iOS 应用的发布流程一直是开发链路中最“苹果味”的环节:强依赖 Xcode、必须使用 macOS、各种证书和描述文件配置……对很多跨平台开发者来说,这一套流程并不友好。 特别是当你的项目主要在 Windows 或 Linux 下开发(例如 Flutter、React Na…...
深入浅出WebGL:在浏览器中解锁3D世界的魔法钥匙
WebGL:在浏览器中解锁3D世界的魔法钥匙 引言:网页的边界正在消失 在数字化浪潮的推动下,网页早已不再是静态信息的展示窗口。如今,我们可以在浏览器中体验逼真的3D游戏、交互式数据可视化、虚拟实验室,甚至沉浸式的V…...
2025.6.9总结(利与弊)
凡事都有两面性。在大厂上班也不例外。今天找开发定位问题,从一个接口人不断溯源到另一个 接口人。有时候,不知道是谁的责任填。将工作内容分的很细,每个人负责其中的一小块。我清楚的意识到,自己就是个可以随时替换的螺丝钉&…...
计算机系统结构复习-名词解释2
1.定向:在某条指令产生计算结果之前,其他指令并不真正立即需要该计算结果,如果能够将该计算结果从其产生的地方直接送到其他指令中需要它的地方,那么就可以避免停顿。 2.多级存储层次:由若干个采用不同实现技术的存储…...
java+webstock
maven依赖 <dependency><groupId>org.java-websocket</groupId><artifactId>Java-WebSocket</artifactId><version>1.3.5</version></dependency><dependency><groupId>org.apache.tomcat.websocket</groupId&…...

代理服务器-LVS的3种模式与调度算法
作者介绍:简历上没有一个精通的运维工程师。请点击上方的蓝色《运维小路》关注我,下面的思维导图也是预计更新的内容和当前进度(不定时更新)。 我们上一章介绍了Web服务器,其中以Nginx为主,本章我们来讲解几个代理软件:…...