这个方法是跟一个同事学习到的,真的是很好用
1.pom.xml文件配置
为pom文件增加以下依赖:
com.baomidou
mybatis-plus-boot-starter
${mybatis-plus.version}
com.baomidou
mybatis-plus
${mybatis-plus.version}
com.baomidou
mybatis-plus-generator
${mybatis-plus.version}
org.freemarker
freemarker
2.3.30
2.pom.xml完整配置
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
com.example
demo2
0.0.1-SNAPSHOT
demo2
Demo project for Spring Boot
1.8
UTF-8
1.8
1.8
3.0.7
2.1.1.RELEASE
5.1.3.RELEASE
4.1.0
2.1.0.RELEASE
4.12
2.8.9
1.7.4
1.43
2.0.4
4.0
RELEASE
1.0.29
5.1.42
1.3.0
org.springframework.boot
spring-boot-starter
com.baomidou
mybatis-plus-boot-starter
${mybatis-plus.version}
com.baomidou
mybatis-plus
${mybatis-plus.version}
com.baomidou
mybatis-plus-generator
${mybatis-plus.version}
org.freemarker
freemarker
2.3.30
org.springframework.boot
spring-boot-devtools
runtime
true
org.springframework.boot
spring-boot-configuration-processor
true
org.projectlombok
lombok
true
org.springframework.boot
spring-boot-starter-test
test
org.junit.vintage
junit-vintage-engine
org.springframework
spring-core
${org.springframework.version}
org.springframework
spring-expression
${org.springframework.version}
org.springframework
spring-beans
${org.springframework.version}
org.springframework
spring-aop
${org.springframework.version}
org.springframework
spring-context
${org.springframework.version}
org.springframework
spring-context-support
${org.springframework.version}
org.springframework
spring-tx
${org.springframework.version}
org.springframework
spring-jdbc
${org.springframework.version}
org.springframework
spring-orm
${org.springframework.version}
org.springframework
spring-oxm
${org.springframework.version}
org.springframework
spring-web
${org.springframework.version}
org.springframework
spring-webmvc
${org.springframework.version}
junit
junit
${junit.version}
test
org.springframework.boot
spring-boot-starter-test
${spring.boot.version}
org.mockito
mockito-core
test
org.mockito
mockito-core
${mockito.version}
test
org.powermock
powermock-module-junit4
${powermock.version}
test
org.powermock
powermock-api-mockito2
${powermock.version}
test
org.jmockit
jmockit
${jmockit.version}
test
org.apache.commons
commons-collections4
${commons-collection4.version}
com.alibaba
druid
${druid.version}
mysql
mysql-connector-java
${mysql-connector-java.version}
org.apache.curator
curator-client
4.0.1
org.apache.zookeeper
zookeeper
org.apache.curator
curator-framework
4.0.1
org.apache.zookeeper
zookeeper
org.apache.curator
curator-recipes
4.0.1
org.apache.zookeeper
zookeeper
org.mortbay.jetty
jetty
6.1.26
com.alibaba
transmittable-thread-local
2.10.2
org.apache.rocketmq
rocketmq-client
4.3.0
org.springframework.boot
spring-boot-maven-plugin
3.启动类
package com.bot.base.data;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
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.FreemarkerTemplateEngine;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* mysql 代码生成器演示例子
*
* @author RL
* @since 2019-09-12
*/
public class MysqlGenerator {
/**
* 读取控制台内容
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("请输入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotEmpty(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}
/**
* RUN THIS
*/
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置(生成在本地)
GlobalConfig gc = new GlobalConfig();
String projectPath = "D://";
gc.setOutputDir(projectPath + "MysqlGenerator/src/main/java");
gc.setAuthor("RL");
gc.setOpen(false);
gc.setIdType(IdType.AUTO);
gc.setDateType(DateType.ONLY_DATE);
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
String baseDataDBUrl = "jdbc:mysql://localhost:3306/base_data?useUnicode=true&characterEncoding=UTF-8";
dsc.setUrl(baseDataDBUrl);
// dsc.setSchemaName("public");
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("123456");
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setEntity("entity");
pc.setMapper("mapper");
pc.setParent("com.bot.base.data");
mpg.setPackageInfo(pc);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
List focList = new ArrayList<>();
focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输入文件名称
return projectPath + "MysqlGenerator/src/main/resources/mapper/"
+ tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
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.setEntityLombokModel(true);
strategy.setSuperEntityColumns("operator","is_delete","create_time","update_time");
strategy.setSuperEntityClass("com.bot.base.data.entity.BaseEntity");
//strategy.setSuperControllerClass("com.bot.base.data.common.BaseController");
strategy.setInclude(("domain_info,skill_info").split(","));
strategy.setControllerMappingHyphenStyle(true);
//strategy.setRestControllerStyle(true);
//strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);
// 选择 freemarker 引擎需要指定如下加,注意 pom 依赖必须有!
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}
4.生成entity文件及常用注解
package com.bot.base.data.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.util.Date;
/**
* MysqlGenerator 中的配置可以生成基类:
* strategy.setSuperEntityColumns("operator","is_delete","create_time","update_time");
* strategy.setSuperEntityClass("com.bot.base.data.entity.BaseEntity");
*/
@Data
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
public class ChannelInfo extends BaseEntity {
private static final long serialVersionUID = 1L;
/**
* id
*/
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
/**
* 渠道id
*/
private Integer channelId;
/**
* 渠道名称(数据库中是json格式,在info文件中用string)
*/
private String channelName;
/**
* 简介说明(value = "`desc`",表示生成sql时的列名,因desc是关键字所以加引号)
*/
@TableField(value = "`desc`")
private String desc;
}
5.entity的基类
package com.bot.base.data.entity;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import java.util.Date;
@Data
public class BaseEntity {
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
private String operator;
@JsonIgnore
@TableLogic
@TableField(fill = FieldFill.INSERT)
private Integer isDelete;
}
6.dto类举例
package com.bot.base.data.sdk.dto;
import lombok.Data;
/**
* @ClassName ChannelDto
* @Description todo
* @Author RL
* @Date 2020/3/23
* @Version 1.0
**/
@Data
public class ChannelDto extends BaseDto{
/**
* 渠道id
*/
private Integer channelId;
/**
* 渠道名称
*/
private String channelName;
/**
* 简介说明
*/
private String desc;
}
7.dto的基类
package com.bot.base.data.sdk.dto;
import com.alibaba.fastjson.JSON;
import lombok.Data;
import java.util.Date;
/**
* @ClassName BaseDto
* @Description todo
* @Author RL
* @Date 2020/3/23
* @Version 1.0
**/
@Data
public class BaseDto {
private Integer id;
private Date createTime;
private Date updateTime;
private String operator;
private boolean isDelete;
@Override
public String toString() {
return JSON.toJSONString(this);
}
}
8.包括部分设置的过滤器
package com.bot.base.data.framework.mybatis;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.util.Date;
@Component
public class FieldFillHandler implements MetaObjectHandler {
private static final Logger logger = LoggerFactory.getLogger(FieldFillHandler.class);
@Override
public void insertFill(MetaObject metaObject) {
logger.info("Mybatis新增数据自动填充通用字段开始......");
Date now = new Date();
this.setInsertFieldValByName("createTime",now,metaObject);
this.setInsertFieldValByName("updateTime",now,metaObject);
this.setInsertFieldValByName("isDelete",0,metaObject);
}
@Override
public void updateFill(MetaObject metaObject) {
logger.info("Mybatis修改数据自动填充通用字段开始......");
Date now = new Date();
this.setUpdateFieldValByName("updateTime",now,metaObject);
}
}
9.对外sdk接口的设计举例
1.接口设计
package com.bot.base.data.sdk;
import com.bot.base.data.sdk.dto.*;
import java.util.List;
/**
* Author: RL
* Date: 2020/4/1
* Time: 10:31
* Description:
* insert接口:参数dto ——> 要插入的列值放入dto相关字段中
* update接口:参数dto ——> 必须有id(作为定位),要更新的列值放入dto相关字段中
* delete接口: 参数id ——> 删除数据的唯一id
* select接口:参数dto ——> 要查询的列值放入dto相关字段中
* 参数pageCurrent ——> 当前页码
* 参数pageTotal ——> 当前页的数据条数
*/
public interface OperateService {
boolean channelInsert(ChannelDto channelDto);
boolean channelUpdate(ChannelDto channelDto);
boolean channelDelete(int id);
List channelSelectByPage(ChannelDto channelDto, int pageCurrent, int pageTotal);
}
2.实现类设计
package com.bot.base.data.operate;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bot.base.data.entity.*;
import com.bot.base.data.sdk.OperateService;
import com.bot.base.data.sdk.dto.*;
import com.bot.base.data.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
/**
* Author: RL
* Date: 2020/3/31
* Time: 10:31
* Description: No Description
*/
@Service
public class OperateServiceImpl implements OperateService {
private Logger logger = LoggerFactory.getLogger(OperateServiceImpl.class);
@Autowired
private IChannelInfoService iChannelInfoService;
@Override
public boolean channelInsert(ChannelDto channelDto) {
if(!isJson(channelDto.getChannelName())){
return false;
}
ChannelInfo info = new ChannelInfo();
BeanUtils.copyProperties(channelDto,info);
boolean result = false;
try{
result = iChannelInfoService.save(info);
} catch (Exception e){
logger.error("insert接口返回有误:" + e);
}
return result;
}
@Override
public boolean channelUpdate(ChannelDto channelDto) {
if(channelDto.getId() == null){
logger.warn("参数中缺少唯一id,update失败");
return false;
}
if(!isJson(channelDto.getChannelName())){
return false;
}
ChannelInfo info = new ChannelInfo();
BeanUtils.copyProperties(channelDto,info);
boolean result = false;
try{
result = iChannelInfoService.updateById(info);
} catch (Exception e){
logger.error("update接口返回有误:" + e);
}
return result;
}
@Override
public boolean channelDelete(int id) {
boolean result = false;
try{
result = iChannelInfoService.removeById(id);
} catch (Exception e){
logger.error("delete接口返回有误:" + e);
}
return result;
}
@Override
public List channelSelectByPage(ChannelDto channelDto, int pageCurrent, int pageTotal) {
IPage iPage = new Page();
iPage.setCurrent(pageCurrent);
iPage.setTotal(pageTotal);
Map map = new HashMap<>();
map.putAll(getCommonMap(channelDto));
map.put("channel_id",channelDto.getChannelId());
map.put("channel_name",channelDto.getChannelName());
map.put("`desc`",channelDto.getDesc());
Wrapper wrapper = new QueryWrapper();
((QueryWrapper) wrapper).allEq(map,false);
List dtoList = new ArrayList<>();
IPage iPages = new Page<>();
try{
iPages = iChannelInfoService.page(iPage,wrapper);
} catch (Exception e){
logger.error("select接口返回有误:" + e);
}
for (int i=0; i
ChannelDto tempDto = new ChannelDto();
BeanUtils.copyProperties(iPages.getRecords().get(i),tempDto);
dtoList.add(tempDto);
}
return dtoList;
}
/**
* dto的共同字段的基类添加查询字段时的公共函数
*/
private Map getCommonMap(BaseDto baseDto){
Map map = new HashMap<>();
map.put("id",baseDto.getId());
map.put("create_time",baseDto.getCreateTime());
map.put("update_time",baseDto.getUpdateTime());
map.put("operator",baseDto.getOperator());
map.put("is_delete",false);
return map;
}
/**
* 判断json是否合法
*/
private boolean isJson(String text){
try {
JSONObject.parseObject(text);
return true;
} catch (Exception e) {
logger.error("JSON字符串非法:{}" + text + e);
return false;
}
}
}
3.自测用例
package com.bot.base.data;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bot.base.data.sdk.OperateService;
import com.bot.base.data.sdk.dto.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.ArrayList;
import java.util.List;
/**
* Author: RL
* Date: 2020/4/1
* Time: 17:25
* Description: No Description
*/
@RunWith(SpringRunner.class)
@ActiveProfiles("local")
@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.NONE)
public class OperateTest {
@Autowired
private OperateService operateService;
@Test
public void testChannel(){
/**
insert
*/
ChannelDto channelDto = new ChannelDto();
channelDto.setChannelId(10007);
channelDto.setChannelName("oooo");
channelDto.setDesc("wowo");
channelDto.setOperator("1");
//System.out.println(operateService.channelInsert(channelDto));
/**
update
*/
ChannelDto channelDto2 = new ChannelDto();
channelDto2.setId(6);
channelDto2.setChannelName("oppo101");
channelDto2.setDesc("oppo version 101");
channelDto2.setDelete(true);
//System.out.println(operateService.channelUpdate(channelDto2));
/**
* delete
*/
//System.out.println(operateService.channelDelete(7));
/**
* select
*/
ChannelDto channelDto3 = new ChannelDto();
//channelDto3.setChannelId(10004);
channelDto3.setDelete(true);
channelDto3.setDesc("sofa");
//List list = operateService.channelSelectByPage(channelDto3,1,10);
//System.out.println(list.size() +"\n" + (list.size() == 0 ? "没有合适的结果" : list).size());
}
}