使用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} />)…...
盘古信息PCB行业解决方案:以全域场景重构,激活智造新未来
一、破局:PCB行业的时代之问 在数字经济蓬勃发展的浪潮中,PCB(印制电路板)作为 “电子产品之母”,其重要性愈发凸显。随着 5G、人工智能等新兴技术的加速渗透,PCB行业面临着前所未有的挑战与机遇。产品迭代…...
Spring Boot 实现流式响应(兼容 2.7.x)
在实际开发中,我们可能会遇到一些流式数据处理的场景,比如接收来自上游接口的 Server-Sent Events(SSE) 或 流式 JSON 内容,并将其原样中转给前端页面或客户端。这种情况下,传统的 RestTemplate 缓存机制会…...
QMC5883L的驱动
简介 本篇文章的代码已经上传到了github上面,开源代码 作为一个电子罗盘模块,我们可以通过I2C从中获取偏航角yaw,相对于六轴陀螺仪的yaw,qmc5883l几乎不会零飘并且成本较低。 参考资料 QMC5883L磁场传感器驱动 QMC5883L磁力计…...
《从零掌握MIPI CSI-2: 协议精解与FPGA摄像头开发实战》-- CSI-2 协议详细解析 (一)
CSI-2 协议详细解析 (一) 1. CSI-2层定义(CSI-2 Layer Definitions) 分层结构 :CSI-2协议分为6层: 物理层(PHY Layer) : 定义电气特性、时钟机制和传输介质(导线&#…...
C# SqlSugar:依赖注入与仓储模式实践
C# SqlSugar:依赖注入与仓储模式实践 在 C# 的应用开发中,数据库操作是必不可少的环节。为了让数据访问层更加简洁、高效且易于维护,许多开发者会选择成熟的 ORM(对象关系映射)框架,SqlSugar 就是其中备受…...
【python异步多线程】异步多线程爬虫代码示例
claude生成的python多线程、异步代码示例,模拟20个网页的爬取,每个网页假设要0.5-2秒完成。 代码 Python多线程爬虫教程 核心概念 多线程:允许程序同时执行多个任务,提高IO密集型任务(如网络请求)的效率…...
成都鼎讯硬核科技!雷达目标与干扰模拟器,以卓越性能制胜电磁频谱战
在现代战争中,电磁频谱已成为继陆、海、空、天之后的 “第五维战场”,雷达作为电磁频谱领域的关键装备,其干扰与抗干扰能力的较量,直接影响着战争的胜负走向。由成都鼎讯科技匠心打造的雷达目标与干扰模拟器,凭借数字射…...
全面解析各类VPN技术:GRE、IPsec、L2TP、SSL与MPLS VPN对比
目录 引言 VPN技术概述 GRE VPN 3.1 GRE封装结构 3.2 GRE的应用场景 GRE over IPsec 4.1 GRE over IPsec封装结构 4.2 为什么使用GRE over IPsec? IPsec VPN 5.1 IPsec传输模式(Transport Mode) 5.2 IPsec隧道模式(Tunne…...
OPenCV CUDA模块图像处理-----对图像执行 均值漂移滤波(Mean Shift Filtering)函数meanShiftFiltering()
操作系统:ubuntu22.04 OpenCV版本:OpenCV4.9 IDE:Visual Studio Code 编程语言:C11 算法描述 在 GPU 上对图像执行 均值漂移滤波(Mean Shift Filtering),用于图像分割或平滑处理。 该函数将输入图像中的…...
Mysql中select查询语句的执行过程
目录 1、介绍 1.1、组件介绍 1.2、Sql执行顺序 2、执行流程 2.1. 连接与认证 2.2. 查询缓存 2.3. 语法解析(Parser) 2.4、执行sql 1. 预处理(Preprocessor) 2. 查询优化器(Optimizer) 3. 执行器…...
