package com.example.demo.zmybatisplusGenerator.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
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;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@EnableTransactionManagement //开启事务
@Configuration //配置类注解
@MapperScan("com.example.demo.zmybatisplus.mapper")
public class MybatisPlusConfig {
//配置拦截器
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
//创建乐观锁拦截器 OptimisticLockerInnerInterceptor
mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
//插件分页拦截器,我的是mysql
// 分页插件放到最后面
mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return mybatisPlusInterceptor;
}
}
maven依赖
<!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-boot-starter -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-generator -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.5.5</version>
</dependency>
<!-- 添加模板引擎,thymeleaf 还有freemarker都是模板引擎 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<!--mybatis-plus 代码生成器的模板引擎-->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.3</version>
</dependency>
<!-- alibaba的druid数据库连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<!-- mysql连接 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
package com.example.demo.zmybatisplusGenerator;
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.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.baomidou.mybatisplus.generator.fill.Column;
import java.sql.Types;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
//自定义模板生成
public class CodeGeneratorPlus {
public static void main(String[] args) {
String projectPath = System.getProperty("user.dir"); //获取当前项目路径
FastAutoGenerator.create("jdbc:mysql://39.107.93.66:3306/testAll?useUnicode=true&characterEncoding=utf-8&useSSL=true&allowMultiQueries=true",
"root",
"fxMC52YcY3U")
// 全局配置
.globalConfig(builder -> {
builder
.enableSwagger() // 是否启用swagger注解
.author("lxb") // 作者名称
.dateType(DateType.ONLY_DATE) // 时间策略
.commentDate("yyyy-MM-dd") // 注释日期
.outputDir(projectPath + "/src/main/java") // 输出目录
.disableOpenDir(); // 生成后禁止打开所生成的系统目录
})
//java和数据库字段的类型转换
.dataSourceConfig(builder -> builder.typeConvertHandler((globalConfig, typeRegistry, metaInfo) -> {
int typeCode = metaInfo.getJdbcType().TYPE_CODE;
if (typeCode == Types.SMALLINT || typeCode == Types.TINYINT) {
// 自定义类型转换
return DbColumnType.INTEGER;
}
return typeRegistry.getColumnType(metaInfo);
}))
// 包配置
.packageConfig(builder -> {
builder
.parent("com.example.demo.zmybatisplusGenerator") // 父包名
.moduleName("test") // 模块包名
.controller("controller")
.entity("entity") // 实体类包名
.service("service") // service包名
.serviceImpl("service.impl") // serviceImpl包名
.mapper("mapper") // mapper包名
.xml("mapper.xml")
.pathInfo(Collections.singletonMap(OutputFile.xml, projectPath + "/src/main/resources/generator/mapper/xml")).build();
})
// 策略配置
.strategyConfig(builder -> {
builder.enableCapitalMode()//驼峰
.enableSkipView()//跳过视图
.disableSqlFilter()
// .addTablePrefix("t_") // 增加过滤表前缀
// .addTableSuffix("_db") // 增加过滤表后缀
// .addFieldPrefix("t_") // 增加过滤字段前缀
// .addFieldSuffix("_field") // 增加过滤字段后缀
// .addInclude("test") // 表匹配
// Entity 策略配置
.entityBuilder()
.enableFileOverride()
.enableLombok() // 开启lombok
.enableChainModel() // 链式
.enableRemoveIsPrefix() // 开启boolean类型字段移除is前缀
.enableTableFieldAnnotation() //开启生成实体时生成的字段注解
.versionColumnName("version") // 乐观锁数据库字段
.versionPropertyName("version") // 乐观锁实体类名称
.logicDeleteColumnName("delflag") // 逻辑删除数据库中字段名
.logicDeletePropertyName("delFlag") // 逻辑删除实体类中的字段名
.naming(NamingStrategy.underline_to_camel) // 表名 下划线 -》 驼峰命名
.columnNaming(NamingStrategy.underline_to_camel) // 字段名 下划线 -》 驼峰命名
.idType(IdType.ASSIGN_ID) // 主键生成策略 雪花算法生成id
.formatFileName("%s") // Entity 文件名称
.addTableFills(new Column("create_time", FieldFill.INSERT)) // 表字段填充
.addTableFills(new Column("update_time", FieldFill.INSERT_UPDATE)) // 表字段填充
//.enableColumnConstant()
//.enableActiveRecord()//MPlus中启用ActiveRecord模式,生成的实体类会继承activerecord.Model类,直接进行数据库操作
// Controller 策略配置
.controllerBuilder()
.enableFileOverride()
.enableHyphenStyle()
.enableRestStyle() // 开启@RestController
.formatFileName("%sController") // Controller 文件名称
// Service 策略配置
.serviceBuilder()
.enableFileOverride()
.formatServiceFileName("%sService") // Service 文件名称
.formatServiceImplFileName("%sServiceImpl") // ServiceImpl 文件名称
// Mapper 策略配置
.mapperBuilder()
.enableFileOverride()
.enableMapperAnnotation() // 开启@Mapper
.enableBaseColumnList() // 启用 columnList (通用查询结果列)
.enableBaseResultMap() // 启动resultMap
.formatMapperFileName("%sMapper") // Mapper 文件名称
.formatXmlFileName("%sMapper"); // Xml 文件名称
})
.templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
.templateConfig(builder -> {
builder.controller("/templates/controller.java")
.service("/templates/service.java")
.serviceImpl("/templates/serviceImpl.java")
//.mapper()
.build();
})
.execute(); // 执行
}
}
controller.java.ftl
package ${package.Controller};
import ${package.Entity}.${entity};
import ${package.Service}.${table.serviceName};
import io.swagger.annotations.ApiOperation;
<#--import org.apache.shiro.authz.annotation.Logical;-->
<#--import org.apache.shiro.authz.annotation.RequiresPermissions;-->
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.validation.constraints.NotBlank;
import javax.validation.Valid;
import java.util.List;
<#--import com.common.res.DataResult;-->
<#if restControllerStyle>
<#else>
import org.springframework.stereotype.Controller;
</#if>
<#if superControllerClassPackage??>
import ${superControllerClassPackage};
</#if>
/**
* @author ${author}
* @since ${date}
*/
<#if restControllerStyle>
@RestController
<#else>
@Controller
</#if>
@RequestMapping("/<#if controllerMappingHyphenStyle>${controllerMappingHyphen}<#else>${table.entityPath}#if>")
<#if kotlin>
class ${table.controllerName}<#if superControllerClass??> : ${superControllerClass}()</#if>
<#else>
<#if superControllerClass??>
public class ${table.controllerName} extends ${superControllerClass} {
<#else>
public class ${table.controllerName} {
</#if>
@Autowired
private ${table.serviceName} ${table.serviceName?uncap_first};
@GetMapping("/selectOne")
<#-- @RequiresPermissions("sys:${table.entityName?uncap_first}:list")-->
@ApiOperation("${table.entityName}查询单个")
public ${table.entityName} get${table.entityName}(@RequestParam("id") Integer id){
${table.entityName} ${table.entityName?uncap_first}One = ${table.entityName?uncap_first}Service.get${table.entityName}( id);
return ${table.entityName?uncap_first}One;
}
@GetMapping("/listAll")
<#-- @RequiresPermissions("sys:${table.entityName?uncap_first}:list")-->
@ApiOperation("${table.entityName}查询全部")
public List<${table.entityName}> getAll${table.entityName}(){
List<${table.entityName}> ${table.entityName?uncap_first}List = ${table.entityName?uncap_first}Service.getAll${table.entityName}();
return ${table.entityName?uncap_first}List;
}
@PostMapping("/add")
<#-- @RequiresPermissions("sys:${table.entityName?uncap_first}:add")-->
@ApiOperation("${table.entityName}新增")
public Object add(@Valid @RequestBody ${table.entityName} ${table.entityName?uncap_first}) {
${table.entityName?uncap_first}Service.add( ${table.entityName?uncap_first});
return null;
}
@PutMapping("/update")
<#-- @RequiresPermissions("sys:${table.entityName?uncap_first}:update")-->
@ApiOperation("${table.entityName}修改")
public int update(@Valid @RequestBody ${table.entityName} ${table.entityName?uncap_first}) {
int num = ${table.entityName?uncap_first}Service.modify( ${table.entityName?uncap_first});
return num;
}
@DeleteMapping(value = "/delete/{ids}")
<#-- @RequiresPermissions("sys:${table.entityName?uncap_first}:delete")-->
@ApiOperation("${table.entityName}删除(单个条目)")
public Object remove(@NotBlank(message = "{required}") @PathVariable String ids) {
${table.entityName?uncap_first}Service.remove(ids);
return null;
}
}
</#if>
service.java.ftl
package ${package.Service};
import ${package.Entity}.${entity};
import ${superServiceClassPackage};
import java.util.List;
/**
* @author ${author}
* @since ${date}
*/
<#if kotlin>
interface ${table.serviceName} : ${superServiceClass}<${entity}>
<#else>
public interface ${table.serviceName} extends ${superServiceClass}<${entity}> {
/**
* ${table.entityName!}详情
* @param
* @return
*/
${table.entityName} get${table.entityName}( Integer id);
/**
* ${table.entityName!}详情
* @param
* @return
*/
List<${table.entityName}> getAll${table.entityName}();
/**
* ${table.entityName!}新增
* @param ${table.entityName?uncap_first} 根据需要进行传值
* @return
*/
void add(${entity} ${table.entityName?uncap_first});
/**
* ${table.entityName!}修改
* @param ${table.entityName?uncap_first} 根据需要进行传值
* @return
*/
int modify(${entity} ${table.entityName?uncap_first});
/**
* ${table.entityName!}删除
* @param ids
* @return
*/
void remove(String ids);
}
</#if>
serviceImpl.java.ftl
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 org.springframework.beans.factory.annotation.Autowired;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import java.util.List;
import java.util.Arrays;
/**
* ${table.comment!} 服务实现类
*
* @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
${table.entityName}Mapper ${table.entityName?uncap_first}Mapper;
@Override
public ${table.entityName} get${table.entityName}(Integer id){
return ${table.entityName?uncap_first}Mapper.selectById(id);
}
@Override
public List<${table.entityName}> getAll${table.entityName}(){
return ${table.entityName?uncap_first}Mapper.selectList(null);
}
@Override
public void add( ${table.entityName} ${table.entityName?uncap_first}) {
${table.entityName?uncap_first}Mapper.insert(${table.entityName?uncap_first});
}
@Override
public int modify( ${table.entityName} ${table.entityName?uncap_first}) {
//乐观锁更新
${table.entityName} current${table.entityName}= ${table.entityName?uncap_first}Mapper.selectById(${table.entityName?uncap_first}.getId());
${table.entityName?uncap_first}.setVersion(current${table.entityName}.getVersion());
return ${table.entityName?uncap_first}Mapper.updateById(${table.entityName?uncap_first});
}
@Override
public void remove( String ids) {
if(StringUtils.isNotEmpty(ids)){
String[] array = ids.split(",");
if (!CollectionUtils.isEmpty(Arrays.asList(array))) {
${table.entityName?uncap_first}Mapper.deleteBatchIds(Arrays.asList(array));
}
}
}
}
</#if>