1、导入相关依赖
<dependencies>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.17</version>
</dependency>
<!-- <dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-annotation</artifactId>
<version>3.4.0</version>
<scope>compile</scope>
</dependency>-->
</dependencies>
2、启动生成代码配置类
package cn.zxq;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
public class GeneratorCode {
private static final String BUNDLE_CONFIG_NAME = "mybatis-plus-config";
public static void main(String[] args) {
//用来获取Mybatis-Plus.properties文件的配置信息
ResourceBundle rb = ResourceBundle.getBundle(BUNDLE_CONFIG_NAME); //不要加后缀
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
gc.setFileOverride(false);
gc.setActiveRecord(true);// 开启 activeRecord 模式
gc.setEnableCache(false);// XML 二级缓存
gc.setBaseResultMap(false);// XML ResultMap
gc.setBaseColumnList(false);// XML columList
gc.setOpen(false);//生成代码后是否打开生成文件的文件夹窗口
gc.setAuthor(rb.getString("author"));
gc.setSwagger2(true); //实体属性 Swagger2 注解
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setDbType(DbType.MYSQL);
dsc.setTypeConvert(new MySqlTypeConvert());
dsc.setDriverName(rb.getString("jdbc.driver"));
dsc.setUsername(rb.getString("jdbc.user"));
dsc.setPassword(rb.getString("jdbc.pwd"));
dsc.setUrl(rb.getString("jdbc.url"));
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setParent(rb.getString("parent")); //设置根包
pc.setController(rb.getString("controller")); //设置控制层的controller包名
pc.setService(rb.getString("service")); //设置生成的service接口包名
pc.setServiceImpl(rb.getString("service.impl"));
pc.setEntity(rb.getString("domain"));
pc.setMapper(rb.getString("mapper"));
mpg.setPackageInfo(pc);
//设置需要生成哪些模板
TemplateConfig templateConfig = new TemplateConfig();
templateConfig.setService(null); //不生成接口类
mpg.setTemplate(templateConfig);
//配置自定义模板生成的文件的保存路径
List<FileOutConfig> focList = new ArrayList<FileOutConfig>();
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// Map<String, Object> map = new HashMap<String, Object>();
// map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-rb");
// this.setMap(map);
}
};
//controller的输出配置
focList.add(new FileOutConfig("/templates/controller.java.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
//合并好的内容输出到哪儿?
return rb.getString("OutputDirController") + rebulidToOutputPath(rb.getString("controller")) + tableInfo.getEntityName() + "Controller.java";
}
});
//service接口的输出配置
focList.add(new FileOutConfig("/templates/service.java.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
return rb.getString("OutputDirServiceMapper") + rebulidToOutputPath(rb.getString("service")) + "I" + tableInfo.getEntityName() + "Service.java";
}
});
focList.add(new FileOutConfig("/templates/serviceImpl.java.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
return rb.getString("OutputDirServiceMapper") + rebulidToOutputPath(rb.getString("service.impl")) + tableInfo.getEntityName() + "ServiceImpl.java";
}
});
focList.add(new FileOutConfig("/templates/mapper.java.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
return rb.getString("OutputDirServiceMapper") + rebulidToOutputPath(rb.getString("mapper")) + tableInfo.getEntityName() + "Mapper.java";
}
});
// 调整 domain 生成目录演示
focList.add(new FileOutConfig("/templates/entity.java.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
return rb.getString("OutputDirBase") + rebulidToOutputPath(rb.getString("domain")) + tableInfo.getEntityName() + ".java";
}
});
//query的输出配置
focList.add(new FileOutConfig("/templates/query.java.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
return rb.getString("OutputDirBase") + rebulidToOutputPath(rb.getString("query")) + tableInfo.getEntityName() + "Query.java";
}
});
// 调整 xml 生成目录演示
focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
return rb.getString("OutputDirXml") + rebulidToOutputPath(rb.getString("mapper")) + tableInfo.getEntityName() + "Mapper.xml";
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
// strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
strategy.setEntityLombokModel(true);//设置实体类支持lombok
strategy.setRestControllerStyle(true);
// 公共父类
// strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
strategy.setInclude(rb.getString("tableNames").split(","));
//设置表的前缀
String table_prefix = rb.getString("table_prefix");
if (StringUtils.isNoneBlank(table_prefix)) {
strategy.setTablePrefix(table_prefix.split(","));// 此处可以修改为您的表前缀
}
mpg.setStrategy(strategy);
mpg.execute();
}
/**
* 重新组装代码生成保存的controller/service/impl/mapper/domain具体包地址
*
* @return
*/
private static String rebulidToOutputPath(String _package) {
ResourceBundle rb = ResourceBundle.getBundle(BUNDLE_CONFIG_NAME); //不要加后缀
String parent = rb.getString("parent") + "." + _package;
String parentPath = StringUtils.replaceAll(parent, "\\.", "/");
return "/" + parentPath + "/";
}
}
3.1、修改resources配置文件
#controller代码输出基本路径 //生成代码的路径
OutputDirController=E:/hrm-workspace/my-cn-zxq/spring-security-demo/src/main/java
#service/mapper代码输出基本路径
OutputDirServiceMapper=E:/hrm-workspace/my-cn-zxq/spring-security-demo/src/main/java
#mapper.xml SQL映射文件目录
OutputDirXml=E:/hrm-workspace/my-cn-zxq/spring-security-demo/src/main/resources
#domain的输出路径
OutputDirBase=E:/hrm-workspace/my-cn-zxq/spring-security-demo/src/main/java
#设置作者
author=zxq
#自定义包路径
#:基础包的路径
#项目根包
parent=cn.zxq
#controller包名
controller=controller
#service包名 不生成service接口
service=service
#service实现类包名
service.impl=service.impl
#mapper数据库操作层包名
mapper=mapper
#数据表对应javabean包名
domain=domain
#自定义查询条件包名
query=query
#去除表的前缀
table_prefix=t_
#需要自动生成的表名
tableNames=oauth_client_details,oauth_code,persistent_logins,t_permission,t_role,t_role_permission,t_user_role,t_vip_user
#数据库连接信息
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql:///hrm-security?serverTimezone=Asia/Shanghai&characterEncoding=utf-8
jdbc.user=root
jdbc.pwd=123456
3.2、修改templates下的controller.java.vm配置文件
package ${package.Controller};
//这里要先设置idea的自动导包功能。代码生成后,重新打开该文件,让idea自动帮助导包
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cn.zxq.utils.PageList; //改成自己的那个工具类的位置
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/${table.entityPath}")
public class ${entity}Controller {
@Autowired
public I${entity}Service ${table.entityPath}Service;
/**
* 保存和修改公用的
* @param ${table.entityPath} 传递的实体
* @return Ajaxresult转换结果
*/
@RequestMapping(value = "/save", method = RequestMethod.POST)
public AjaxResult save(@RequestBody ${entity} ${table.entityPath}) {
try {
if (${table.entityPath}.getId() != null){
${table.entityPath}Service.updateById(${table.entityPath});
}else{
${table.entityPath}Service.save(${table.entityPath});
}
return AjaxResult.me();
} catch (Exception e) {
e.printStackTrace();
return AjaxResult.me().setSuccess(false).setMessage("保存对象失败!" + e.getMessage());
}
}
/**
* 删除对象信息
* @param id
* @return
*/
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public AjaxResult delete(@PathVariable("id") Long id) {
try {
${table.entityPath}Service.removeById(id);
return AjaxResult.me();
} catch (Exception e) {
e.printStackTrace();
return AjaxResult.me().setSuccess(false).setMessage("删除对象失败!" + e.getMessage());
}
}
//获取用户
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public ${entity} get(@PathVariable("id") Long id) {
return ${table.entityPath}Service.getById(id);
}
/**
* 查看所有的员工信息
* @return
*/
@RequestMapping(value = "/list", method = RequestMethod.GET)
public List<${entity}> list() {
return ${table.entityPath}Service.list();
}
/**
* 分页查询数据(不带查询条件))
*
* @param query 查询对象
* @return PageList 分页对象
*/
@RequestMapping(value = "/pagelist", method = RequestMethod.POST)
public PageList<${entity}> json(@RequestBody ${entity}Query query) {
Page<${entity}> page = new Page<${entity}>(query.getPage(), query.getRows());
page = ${table.entityPath}Service.page(page);
return new PageList<${entity}>( page.getTotal(),page.getRecords());
}
}
3.2、修改templates下的query.java.vm的配置文件
package cn.zxq.query; //设置生成的路径
import lombok.Data;
/**
*
* @author ${author}
* @since ${date}
*/
@Data
public class ${table.entityName}Query extends BaseQuery{
}
这就可以给你完成一键生成代码了,真得很实用,为java开发者减少了不少事呀!!!