第一种-简易式
代码自动生成:AutoGenerator是MyBatis-Plus的代码生成器,通过AutoGenerator可以快速生成Controller、Service、Mapper、Entity等各个模块的代码,提升了开发效率。
1.准备工作
首先在数据库中创建好,数据库和要生成代码对应的表。然后创建简易Springboot项目。网上资源很多可自行搜索。
2.代码实现
- baseEntity:用来写一些公共字段。例如:创建时间,创建人等
- baseController:用来写基础公共的控制
pom.xml 文件内容
<?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>2.7.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.hn.yuan</groupId>
<artifactId>mybatisplus-one</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>mybatisplus-one</name>
<description>Demo project for Spring Boot</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<!--spring项目启动器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--通过注解消除实际开发中的样板式代码-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!--spring项目测试启动器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<!--mybatis-plus启动器-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.0</version>
</dependency>
<!--mysql数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.35</version>
</dependency>
<!--代码生成器-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.3.0</version>
</dependency>
<!--模板引擎-->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.28</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
创建baseController和BaseEntity类
package com.hn.yuan.common.dao;
public class BaseController {
}
package com.hn.yuan.common.entity;
import java.io.Serializable;
public class BaseEntity implements Serializable {
}
创建代码生成类(最好放入测试包中)。代码生成过程中需使用Lombok插件,需提前在idea安装好。
package com.hn.yuan;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
public class MysqlGenerator {
public static void main(String[] args) {
AutoGenerator mpg = new AutoGenerator();
//1、全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java"); //生成路径(一般都是生成在此项目的src/main/java下面)
gc.setAuthor("XIAOCAO"); //设置作者
gc.setOpen(false);
gc.setFileOverride(true); //第二次生成会把第一次生成的覆盖掉
gc.setServiceName("%sService"); //生成的service接口名字首字母是否为I,这样设置就没有
gc.setBaseResultMap(true); //生成resultMap
mpg.setGlobalConfig(gc);
//2、数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/yuan_productlist?useUnicode=true&characterEncoding=UTF-8&useSSL=false");
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("root");
mpg.setDataSource(dsc);
// 3、包配置
PackageConfig pc = new PackageConfig();
//pc.setModuleName("sys");
pc.setParent("com.hn.yuan");
mpg.setPackageInfo(pc);
// 4、策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setSuperControllerClass("com.hn.yuan.common.dao.BaseController");
strategy.setSuperEntityClass("com.hn.yuan.common.entity.BaseEntity");
// strategy.setTablePrefix("t_"); // 表名前缀
strategy.setEntityLombokModel(true); //使用lombok
strategy.setRestControllerStyle(true);
strategy.setInclude("orders"); // 逆向工程使用的表 如果要生成多个,这里可以传入String[]
mpg.setStrategy(strategy);
//5、执行
mpg.execute();
}
}
执行即可!以下为项目生成结果截图。
第二种-自定义模板
1.准备工作
前置知识:Velocity语法使用链接:http://www.51gjie.com/javaweb/896.html
自定义模板使用的是Velocity模板引擎(也可使用Freemarker)
- 需提前学习Velocity相关语法(语法很简单)
注意:velocity的注释在一行中一定要顶头(否则生成的java,会在格式中多空格)
首先在数据库中创建好,数据库和要生成代码对应的表。然后创建简易Springboot项目。网上资源很多可自行搜索。
2.代码实现
- baseEntity:用来写一些公共字段。例如:创建时间,创建人等
- baseController:用来写基础公共的控制
3.Velocity展示
controller层引擎模板
package ${package.Controller};
import org.springframework.web.bind.annotation.RequestMapping;
#if(${restControllerStyle})
import org.springframework.web.bind.annotation.RestController;
#else
import org.springframework.stereotype.Controller;
#end
#if(${superControllerClassPackage})
import ${superControllerClassPackage};
#end
/**
* @auther ${author}
* @create ${cfg.dateTime}
* @describe $!{table.comment}前端控制器
*/
#if(${restControllerStyle})
@RestController
#else
@Controller
#end
@RequestMapping("#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} {
#end
}
#end
entity层引擎模板
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.Data;
#if(${chainModel})
import lombok.experimental.Accessors;
#end
#end
/**
* <p>
* $!{table.comment}
* </p>
*
* @author ${author}
* @since ${date}
*/
#if(${entityLombokModel})
@Data
#if(${chainModel})
@Accessors(chain = true)
#end
#end
#if(${table.convert})
@TableName("${schemaName}${table.name}")
#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" != "")
/**
* ${field.comment}
*/
#end
#if(${field.keyFlag})
## 主键
#if(${field.keyIdentityFlag})
@TableId(value = "${field.name}", type = IdType.AUTO)
#elseif(!$null.isNull(${idType}) && "$!idType" != "")
@TableId(value = "${field.name}", type = IdType.${idType})
#elseif(${field.convert})
@TableId("${field.name}")
#end
## 普通字段
#elseif(${field.fill})
## ----- 存在字段填充设置 -----
#if(${field.convert})
@TableField(value = "${field.name}", fill = FieldFill.${field.fill})
#else
@TableField(fill = FieldFill.${field.fill})
#end
#elseif(${field.convert})
@TableField("${field.name}")
#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")
#end
public ${field.propertyType} ${getprefix}${field.capitalName}() {
return ${field.propertyName};
}
#if(${chainModel})
public ${entity} set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
#else
public void set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
#end
this.${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};
#else
return 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
}
mapper层引擎模板
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}
* @since ${date}
*/
#if(${mapperAnnotation})
@Mapper
#end
public interface ${table.mapperName} extends ${superMapperClass}<${entity}> {
}
xml层引擎模板
<?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}">
#if(${enableCache})
<!-- 开启二级缓存 -->
<cache type="${cacheClassName}"/>
#end
#if(${baseResultMap})
<!-- 通用查询映射结果 -->
<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>
#end
#if(${baseColumnList})
<!-- 通用查询结果列 -->
<sql id="Base_Column_List">
#foreach($field in ${table.commonFields})
${field.columnName},
#end
${table.fieldNames}
</sql>
#end
</mapper>
service层引擎模板
package ${package.Service};
import ${package.Entity}.${entity};
import ${superServiceClassPackage};
/**
* <p>
* $!{table.comment} 服务类
* </p>
*
* @author ${author}
* @since ${date}
*/
public interface ${table.serviceName} extends ${superServiceClass}<${entity}> {
}
serviceimpl层引擎模板
package ${package.ServiceImpl};
import ${package.Entity}.${entity};
import ${package.Mapper}.${table.mapperName};
import ${package.Service}.${table.serviceName};
import ${superServiceImplClassPackage};
import org.springframework.stereotype.Service;
/**
* <p>
* $!{table.comment} 服务实现类
* </p>
*
* @author ${author}
* @since ${date}
*/
@Service
public class ${table.serviceImplName} extends ${superServiceImplClass}<${table.mapperName}, ${entity}> implements ${table.serviceName} {
}
创建代码生成类(最好放入测试包中)。代码生成过程中需使用Lombok插件,需提前在idea安装好。
package com.hn.yuan;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;
import java.util.ArrayList;
import java.util.List;
/**
* springboot-plus代码生成器入口类
*
* @author
* @date
*/
public class CodeGenerator {
private static final String USER_NAME = "root" ;
private static final String PD = "root" ;
private static final String DRIVER_NAME = "com.mysql.jdbc.Driver" ;
private static final String DRIVER_URL = "jdbc:mysql://localhost:3306/baoxian_user?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=UTF-8&useSSL=false" ;
private static final String PARENT_PACKAGE = "com.hn.yuan" ;
private static final String SUPER_ENTITY = PARENT_PACKAGE + ".common.entity.BaseEntity" ;
private static final String[] SUPER_ENTITY_COMMON_COLUMNS = new String[]{};
private static final String SUPER_CONTROLLER = PARENT_PACKAGE + ".common.dao.BaseController" ;
// private static final String SUPER_SERVICE = PARENT_PACKAGE + ".common.service.BaseService" ;
// private static final String SUPER_SERVICE_IMPL = PARENT_PACKAGE + ".common.service.impl.BaseServiceImpl" ;
private static final String PROJECT_PACKAGE_PATH = "com/hn/yuan" ;
// ############################ 配置部分start ############################
// 模块名称
private static final String MODULE_NAME = "" ;
// 作者
private static final String AUTHOR = "XIAOCAO" ;
// 生成的表名称
private static final String TABLE_NAME = "orders" ;
// 主键数据库列名称
private static final String PK_ID_COLUMN_NAME = "id" ;
// 代码生成策略 true:All/false:SIMPLE
private static final boolean GENERATOR_STRATEGY = true;
// 分页列表查询是否排序 true:有排序参数/false:无
private static final boolean PAGE_LIST_ORDER = false;
// ############################ 配置部分end ############################
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = "F:/Xxlearning/Lx/mybatisTest/mybatisplusOne" ;
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor(AUTHOR);
gc.setOpen(true); // 是否打开输出目录
// gc.setSwagger2(true);// 启用swagger注解
gc.setIdType(IdType.ID_WORKER); // 主键类型:ID_WORKER
gc.setServiceName("%sService"); // 自定义文件命名,注意 %s 会自动填充表实体属性!
gc.setFileOverride(true); // 是否覆盖已有文件
gc.setDateType(DateType.ONLY_DATE);// 设置日期类型为Date
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl(DRIVER_URL);
// dsc.setSchemaName("public");
dsc.setDriverName(DRIVER_NAME);
dsc.setUsername(USER_NAME);
dsc.setPassword(PD);
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName(MODULE_NAME);
pc.setParent(PARENT_PACKAGE);
pc.setController("controller");
mpg.setPackageInfo(pc);
String projectPathCommon = projectPath + "/src/main/java/com/hn/yuan" ;
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
}
};
//自定义输出配置
List<FileOutConfig> focList = new ArrayList<>();
// 自定义配置会被优先输出
focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输入文件名称
return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
focList.add(new FileOutConfig("/templates/entity.java.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return projectPathCommon + "/entity/" + tableInfo.getEntityName() + StringPool.DOT_JAVA;
}
});
focList.add(new FileOutConfig("/templates/controller.java.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return projectPathCommon + "/controller/" + tableInfo.getControllerName() + StringPool.DOT_JAVA;
}
});
focList.add(new FileOutConfig("/templates/service.java.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return projectPathCommon + "/service/" + tableInfo.getServiceName() + StringPool.DOT_JAVA;
}
});
focList.add(new FileOutConfig("/templates/serviceImpl.java.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return projectPathCommon + "/service/impl/" + tableInfo.getServiceImplName() + StringPool.DOT_JAVA;
}
});
focList.add(new FileOutConfig("/templates/mapper.java.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return projectPathCommon + "/mapper/" + tableInfo.getMapperName() + StringPool.DOT_JAVA;
}
});
cfg.setFileOutConfigList(focList);
//--------------- 模板配置 -----------------
mpg.setCfg(cfg);
mpg.setTemplate(new TemplateConfig().setXml(null));
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel); //数据库表映射到实体的命名策略
strategy.setColumnNaming(NamingStrategy.underline_to_camel); //数据库表字段映射到实体的命名策略
strategy.setSuperEntityClass(SUPER_ENTITY);
strategy.setEntityLombokModel(true); //lombok 模型
strategy.setRestControllerStyle(true); //生成 @Controller 控制器
strategy.setSuperControllerClass(SUPER_CONTROLLER);
// strategy.setSuperServiceClass(SUPER_SERVICE);
// strategy.setSuperServiceImplClass(SUPER_SERVICE_IMPL);
strategy.setInclude(TABLE_NAME);
strategy.setSuperEntityColumns(SUPER_ENTITY_COMMON_COLUMNS);
strategy.setControllerMappingHyphenStyle(true);
/**
* 注意,根据实际情况,进行设置
* 当表名称的前缀和模块名称一样时,会去掉表的前缀
* 比如模块名称为user,表明为user_info,则生成的实体名称是Info.java,一定要注意
*/
//strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);
// mpg.setTemplateEngine(new VelocityTemplateEngine());
mpg.execute();
}
}
执行即可!以下为项目生成结果截图。
第三种-插件式
1.准备工作
idea代码生成插件EasyCode
通过idea安装:File->Settings->Plugins
ps:如果插件没有生效,建议关闭重新打开idea
安装完成插件后-添加数据源
根据自己的数据库添加对应的数据源,之后我们可以直接通过数据源生成业务代码
勾选自己想要的固定模板
生成结果-效果图
Springboot-Easycode插件自定义模板
背景:做项目,感觉官方给予的固定模板,不是很符合自己的口味。那就自己使用自己定义的模板。
数据类型映射 打开idea ->Settings ->Easy code Type
Mapper是数据类型映射,数据库的字段类型与实体类属性的类型相对应,可做参考。
定义-自己的自定义模板
下面提供一套自定义模板-仅供参考
实体类 entity.java
##引入宏定义
$!define
##使用宏定义设置回调(保存位置与文件后缀)
#save("/entity", ".java")
##使用宏定义设置包后缀
#setPackageSuffix("entity")
##使用全局变量实现默认包导入
$!autoImport
import java.io.Serializable;
import lombok.Data;
##
####使用宏定义实现类注释信息
###tableComment("实体类")
@Data
public class $!{tableInfo.name} implements Serializable {
private static final long serialVersionUID = $!tool.serial();
#foreach($column in $tableInfo.fullColumn)
#if(${column.comment})/**
* ${column.comment}
*/
#end
private $!{tool.getClsNameByFullName($column.type)} $!{column.name};
## private $!{tool.getClsNameByFullName($column.type)} $!{tool.firstUpperCase($column.name)};
#end
##若没有使用lombok插件,该段不要注释,按照默认的模板
###foreach($column in $tableInfo.fullColumn)
####使用宏定义实现get,set方法
###getSetMethod($column)
###end
}
dao层 dao.java
##定义初始变量
#set($tableName = $tool.append($tableInfo.name, "Dao"))
##设置回调
$!callback.setFileName($tool.append($tableName, ".java"))
$!callback.setSavePath($tool.append($tableInfo.savePath, "/dao"))
##拿到主键
#if(!$tableInfo.pkColumn.isEmpty())
#set($pk = $tableInfo.pkColumn.get(0))
#end
#if($tableInfo.savePackageName)package $!{tableInfo.savePackageName}.#{end}dao;
import $!{tableInfo.savePackageName}.entity.$!{tableInfo.name};
import java.util.List;
public interface $!{tableName} {
//通过ID查询
$!{tableInfo.name} selectById($!pk.shortType $!pk.name);
//查询所有数据
List<$!{tableInfo.name}> selectAll();
## //通过实体作为筛选条件查询
## List<$!{tableInfo.name}> queryAll($!{tableInfo.name} $!tool.firstLowerCase($!{tableInfo.name}));
//新增数据
int insert($!{tableInfo.name} $!tool.firstLowerCase($!{tableInfo.name}));
//修改数据
int updateById($!{tableInfo.name} $!tool.firstLowerCase($!{tableInfo.name}));
//通过主键id删除数据
int deleteById($!pk.shortType $!pk.name);
}
映射层 mapper.xml
##引入mybatis支持
$!mybatisSupport
##设置保存名称与保存位置
$!callback.setFileName($tool.append($!{tableInfo.name}, "Mapper.xml"))
$!callback.setSavePath($tool.append($tableInfo.savePath, "/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}.dao.$!{tableInfo.name}Dao">
<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>
<sql id="BaseResult">
#allSqlColumn()
</sql>
<!--根据id查询-->
<select id="selectById" resultType="$!{tableInfo.savePackageName}.entity.$!{tableInfo.name}">
select<include refid="BaseResult"/>
from $!tableInfo.obj.name
where $!pk.obj.name = #{$!pk.name}
</select>
<!--查询所有数据-->
<select id="selectAll" resultMap="$!{tableInfo.name}Map">
select<include refid="BaseResult"/>
from $!tableInfo.obj.name
</select>
##
## <!--通过实体作为筛选条件查询-->
## <select id="queryAll" resultMap="$!{tableInfo.name}Map">
## select<include refid="BaseResult"/>
## from $!tableInfo.obj.name
## <where>
###foreach($column in $tableInfo.fullColumn)
## <if test="$!column.name != null#if($column.type.equals("java.lang.String")) and $!column.name != ''#end">
## and $!column.obj.name = #{$!column.name}
## </if>
###end
## </where>
## </select>
<!--新增所有列-->
<insert id="insert" keyProperty="$!pk.name" useGeneratedKeys="true">
insert into $!{tableInfo.obj.name}(<include refid="BaseResult"/>)
values (#null,#foreach($column in $tableInfo.otherColumn)#{$!{column.name}}#if($velocityHasNext), #end#end)
</insert>
<!--通过主键id修改数据-->
<update id="updateById">
update $!{tableInfo.obj.name}
<set>
#foreach($column in $tableInfo.otherColumn)
<if test="$!column.name != null#if($column.type.equals("java.lang.String")) and $!column.name != ''#end">
$!column.obj.name = #{$!column.name},
</if>
#end
</set>
where $!pk.obj.name = #{$!pk.name}
</update>
<!--通过主键id删除-->
<delete id="deleteById">
delete from $!{tableInfo.obj.name} where $!pk.obj.name = #{$!pk.name}
</delete>
</mapper>
service层 sercice.java
##定义初始变量
#set($tableName = $tool.append($tableInfo.name, "Service"))
##设置回调
$!callback.setFileName($tool.append($tableName, ".java"))
$!callback.setSavePath($tool.append($tableInfo.savePath, "/service"))
##拿到主键
#if(!$tableInfo.pkColumn.isEmpty())
#set($pk = $tableInfo.pkColumn.get(0))
#end
#if($tableInfo.savePackageName)package $!{tableInfo.savePackageName}.#{end}service;
import $!{tableInfo.savePackageName}.entity.$!{tableInfo.name};
import java.util.List;
import com.github.pagehelper.PageInfo;
public interface $!{tableName} {
//通过ID查询
$!{tableInfo.name} selectById($!pk.shortType $!pk.name);
//查询所有数据并分页
PageInfo<$!{tableInfo.name}> selectAll(int pageNum, int pageSize);
## //通过实体作为筛选条件查询
## List<$!{tableInfo.name}> queryAll($!{tableInfo.name} $!tool.firstLowerCase($!{tableInfo.name}));
//新增数据
int insert($!{tableInfo.name} $!tool.firstLowerCase($!{tableInfo.name}));
//修改数据
int updateById($!{tableInfo.name} $!tool.firstLowerCase($!{tableInfo.name}));
//通过主键id删除数据
int deleteById($!pk.shortType $!pk.name);
}
service实现类 serciceImpl.java
##定义初始变量
#set($tableName = $tool.append($tableInfo.name, "ServiceImpl"))
##设置回调
$!callback.setFileName($tool.append($tableName, ".java"))
$!callback.setSavePath($tool.append($tableInfo.savePath, "/service/impl"))
##拿到主键
#if(!$tableInfo.pkColumn.isEmpty())
#set($pk = $tableInfo.pkColumn.get(0))
#end
#if($tableInfo.savePackageName)package $!{tableInfo.savePackageName}.#{end}service.impl;
import $!{tableInfo.savePackageName}.entity.$!{tableInfo.name};
import $!{tableInfo.savePackageName}.dao.$!{tableInfo.name}Dao;
import $!{tableInfo.savePackageName}.service.$!{tableInfo.name}Service;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import javax.annotation.Resource;
import java.util.List;
@Service
@Transactional
public class $!{tableName} implements $!{tableInfo.name}Service {
@Autowired
private $!{tableInfo.name}Dao $!tool.firstLowerCase($!{tableInfo.name})Dao;
/**
* 通过ID查询单条数据
* @param $!pk.name 主键
* @return 实例对象
*/
@Override
public $!{tableInfo.name} selectById($!pk.shortType $!pk.name) {
return $!{tool.firstLowerCase($!{tableInfo.name})}Dao.selectById($!pk.name);
}
/**
* 查询多条数据
* @param pageNum 查询起始位置
* @param pageSize 查询条数
* @return 对象列表
*/
@Override
public PageInfo selectAll(int pageNum, int pageSize) {
PageHelper.startPage(pageNum,pageSize);
List<$!{tableInfo.name}> dataList = $!{tool.firstLowerCase($!{tableInfo.name})}Dao.selectAll();
PageInfo<$!{tableInfo.name}> page = new PageInfo<$!{tableInfo.name}>(dataList);
return page;
}
/**
* 新增数据
* @param $!tool.firstLowerCase($!{tableInfo.name}) 实例对象
* @return 实例对象
*/
@Override
public int insert($!{tableInfo.name} $!tool.firstLowerCase($!{tableInfo.name})) {
return $!{tool.firstLowerCase($!{tableInfo.name})}Dao.insert($!tool.firstLowerCase($!{tableInfo.name}));
}
/**
* 修改数据
* @param $!tool.firstLowerCase($!{tableInfo.name}) 实例对象
* @return 实例对象
*/
@Override
public int updateById($!{tableInfo.name} $!tool.firstLowerCase($!{tableInfo.name})) {
return $!{tool.firstLowerCase($!{tableInfo.name})}Dao.updateById($!tool.firstLowerCase($!{tableInfo.name}));
}
/**
* 通过主键id删除数据
* @param $!pk.name 主键
*/
@Override
public int deleteById($!pk.shortType $!pk.name) {
return $!{tool.firstLowerCase($!{tableInfo.name})}Dao.deleteById($!pk.name);
}
}
controller实现类 controller.java
##定义初始变量
#set($tableName = $tool.append($tableInfo.name, "Controller"))
##设置回调
$!callback.setFileName($tool.append($tableName, ".java"))
$!callback.setSavePath($tool.append($tableInfo.savePath, "/controller"))
##拿到主键
#if(!$tableInfo.pkColumn.isEmpty())
#set($pk = $tableInfo.pkColumn.get(0))
#end
#if($tableInfo.savePackageName)package $!{tableInfo.savePackageName}.#{end}controller;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
/**
* $!{tableInfo.comment}($!{tableInfo.name})表控制层
*
* @author $!author
* @since $!time.currTime()
*/
@RestController
@RequestMapping("$!tool.firstLowerCase($tableInfo.name)")
public class $!{tableName} {
}
注意:以上pom.xml 文件可共用。三种方式不用纠结,对于使用的人来说不分优劣,只分好用不好用。
各位看官》创作不易,点个赞!!!
诸君共勉:万事开头难,只愿肯放弃。
免责声明:本文章仅用于学习参考