IController 所有控制器继承该类 实现 getService 方法获得抽象类所有增删改查方法
import com.baomidou.mybatisplus.core.conditions.AbstractWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.gs.game.common.ResponseWrapper;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public abstract class IController<T> {
public abstract IService<T> getService();
@PutMapping(value = "/_insert")
public ResponseWrapper insert(@RequestBody T t){
return new ResponseWrapper(getService().save(t));
}
@PutMapping(value = "/_save")
public ResponseWrapper save(@RequestBody T t){
return new ResponseWrapper(getService().saveOrUpdate(t));
}
@PutMapping(value = "/_update")
public ResponseWrapper update(@RequestBody T t,@RequestParam Map<String,Object> map){
if(ObjectUtils.isEmpty(map)){
return new ResponseWrapper(false);
}
return new ResponseWrapper(getService().update( t ,new QueryWrapper().setEntity(map)));
}
@DeleteMapping(value = "/_delete")
public ResponseWrapper delete(@RequestBody Map<String,Object> map){
if(ObjectUtils.isEmpty(map)){
return new ResponseWrapper(false);
}
return new ResponseWrapper(getService().remove(new QueryWrapper().setEntity(map)));
}
@DeleteMapping(value = "/_deleteById")
public ResponseWrapper deleteById(@RequestParam Map<String,Object> map){
if(ObjectUtils.isEmpty(map)){
return new ResponseWrapper(false);
}
if(ObjectUtils.isEmpty(map.get("id"))){
return new ResponseWrapper(false);
}
return new ResponseWrapper(getService().remove(new QueryWrapper().setEntity(new HashMap(){{
put("id",map.get("id"));
}})));
}
@GetMapping(value = "/_findById")
public ResponseWrapper findById(@RequestParam Map<String,Object> map){
if(ObjectUtils.isEmpty(map)){
return new ResponseWrapper(new HashMap<>());
}
if(ObjectUtils.isEmpty(map.get("id"))){
return new ResponseWrapper(new HashMap<>());
}
return new ResponseWrapper(getService().getOne(new QueryWrapper().setEntity(new HashMap(){{
put("id",map.get("id"));
}})));
}
@GetMapping(value = "/_findOne")
public ResponseWrapper findOne(@RequestParam Map<String,Object> map){
return new ResponseWrapper(getService().getBaseMapper().selectOne(wrapper(map)));
}
@GetMapping(value = "/_find")
public ResponseWrapper find(@RequestParam Map<String,Object> map){
return new ResponseWrapper(getService().getBaseMapper().selectList(wrapper(map)));
}
@GetMapping(value = "/_page")
public ResponseWrapper page(@PageableDefault Page page, @RequestParam Map<String,Object> map){
return new ResponseWrapper( getService().page(pageInit(page), wrapper(map)));
}
public static Page pageInit(Page page){
List<OrderItem> orders = page.getOrders();
if(!ObjectUtils.isEmpty(orders)){
orders.forEach(f ->{
f.setColumn(f.getColumn().replaceAll("[A-Z]", "_$0").toLowerCase());
});
}
return page;
}
public static AbstractWrapper wrapper(Map<String,Object> map){
AbstractWrapper wrapper = new QueryWrapper().setEntity(map);
List<Map> paramList = new ArrayList();
List<Map> orderList = new ArrayList();
for (int i = 0; i < map.keySet().size(); i++) {
Map<String,Object> param = new HashMap<>();
Map<String,Object> order = new HashMap<>();
String parmKey = "["+i+"].";
String orderKey = "orderBy["+i+"].";
map.keySet().forEach(f ->{
if(f.startsWith((parmKey+"type"))){
param.put("type",map.get(f));
}
if(f.startsWith((parmKey+"column"))){
param.put("column",map.get(f));
}
if(f.startsWith((parmKey+"value"))){
param.put("value",map.get(f));
}
if(f.startsWith((orderKey+"column"))){
order.put("column",map.get(f));
}
if(f.startsWith((orderKey+"asc"))){
order.put("asc",map.get(f));
}
});
if(3 == param.keySet().size()){
paramList.add(param);
}
if(!ObjectUtils.isEmpty(order.get("column"))){
orderList.add(order);
}
}
if(!ObjectUtils.isEmpty(paramList)){
for(Map<String,Object> hashMap : paramList){
switch ( (hashMap.get("type") + "") ){
case "eq":
wrapper.eq( (hashMap.get("column")+"").replaceAll("[A-Z]", "_$0").toLowerCase() , (hashMap.get("value")+"") );
break;
case "ne":
wrapper.ne( (hashMap.get("column")+"").replaceAll("[A-Z]", "_$0").toLowerCase() , (hashMap.get("value")+"") );
break;
case "like":
wrapper.like( (hashMap.get("column")+"").replaceAll("[A-Z]", "_$0").toLowerCase() , (hashMap.get("value")+"") );
break;
case "leftlike":
wrapper.likeLeft( (hashMap.get("column")+"").replaceAll("[A-Z]", "_$0").toLowerCase() , (hashMap.get("value")+"") );
break;
case "rightlike":
wrapper.likeRight( (hashMap.get("column")+"").replaceAll("[A-Z]", "_$0").toLowerCase() , (hashMap.get("value")+"") );
break;
case "notlike":
wrapper.notLike( (hashMap.get("column")+"").replaceAll("[A-Z]", "_$0").toLowerCase() , (hashMap.get("value")+"") );
break;
case "gt":
wrapper.gt( (hashMap.get("column")+"").replaceAll("[A-Z]", "_$0").toLowerCase() , (hashMap.get("value")+"") );
break;
case "lt":
wrapper.lt( (hashMap.get("column")+"").replaceAll("[A-Z]", "_$0").toLowerCase() , (hashMap.get("value")+"") );
break;
case "ge":
wrapper.ge( (hashMap.get("column")+"").replaceAll("[A-Z]", "_$0").toLowerCase() , (hashMap.get("value")+"") );
break;
case "le":
wrapper.le( (hashMap.get("column")+"").replaceAll("[A-Z]", "_$0").toLowerCase() , (hashMap.get("value")+"") );
break;
}
}
}
if(!ObjectUtils.isEmpty(orderList)){
orderList.forEach(f ->{
if("false".equals((f.get("asc") + ""))){
wrapper.orderByDesc((f.get("column")+"").replaceAll("[A-Z]", "_$0").toLowerCase());
} else {
wrapper.orderByAsc((f.get("column")+"").replaceAll("[A-Z]", "_$0").toLowerCase());
}
});
}
return wrapper;
}
}
MyController 请求头中添加 entity 实体路径 动态调用执行 基础增删改查方法
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gs.game.common.ResponseWrapper;
import com.gs.game.utils.ApplicationContextutil;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/game/my")
public class MyController {
private String getMapper(){
String entity = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("entity");
entity = entity.substring(entity.indexOf(".") + 1);
String first = entity.substring(0, 1);
String after = entity.substring(1);
entity = first.toLowerCase() + after;
return entity + "Mapper";
}
private String getEntity(){
return "com.gs.game.model." + ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("entity");
}
@PutMapping(value = "/_insert")
public ResponseWrapper insert(@RequestBody Map<String,Object> map ) throws Exception{
return new ResponseWrapper(ApplicationContextutil.getBean(getMapper(), BaseMapper.class).insert(JSON.parseObject(JSON.toJSONString(map),Class.forName(getEntity()))));
}
@PutMapping(value = "/_save")
public ResponseWrapper save(@RequestBody Map<String,Object> map) throws Exception{
BaseMapper mapper = ApplicationContextutil.getBean(getMapper(), BaseMapper.class);
Object object = JSON.parseObject(JSON.toJSONString(map), Class.forName(getEntity()));
if(0 == mapper.updateById(object)){
mapper.insert(object);
}
return new ResponseWrapper(1);
}
@PutMapping(value = "/_update")
public ResponseWrapper update(@RequestBody Map<String,Object> body ,@RequestParam Map<String,Object> param) throws Exception{
if(ObjectUtils.isEmpty(param)){
return new ResponseWrapper(false);
}
return new ResponseWrapper(ApplicationContextutil.getBean(getMapper(), BaseMapper.class).update(JSON.parseObject(JSON.toJSONString(body), Class.forName(getEntity())),new QueryWrapper().setEntity(param)));
}
@DeleteMapping(value = "/_delete")
public ResponseWrapper delete(@RequestBody Map<String,Object> map){
if(ObjectUtils.isEmpty(map)){
return new ResponseWrapper(false);
}
return new ResponseWrapper(ApplicationContextutil.getBean(getMapper(), BaseMapper.class).delete(new QueryWrapper().setEntity(map)));
}
@DeleteMapping(value = "/_deleteById")
public ResponseWrapper deleteById(@RequestParam Map<String,Object> map){
if(ObjectUtils.isEmpty(map.get("id"))){
return new ResponseWrapper(false);
}
return new ResponseWrapper(ApplicationContextutil.getBean(getMapper(), BaseMapper.class).delete(new QueryWrapper().setEntity(new HashMap(){{
put("id",map.get("id"));
}})));
}
@GetMapping(value = "/_findById")
public ResponseWrapper findById(@RequestParam Map<String,Object> map){
if(ObjectUtils.isEmpty(map.get("id"))){
return new ResponseWrapper(new HashMap<>());
}
return new ResponseWrapper(ApplicationContextutil.getBean(getMapper(), BaseMapper.class).selectOne(new QueryWrapper().setEntity(new HashMap(){{
put("id",map.get("id"));
}})));
}
@GetMapping(value = "/_findOne")
public ResponseWrapper findOne(@RequestParam Map<String,Object> map){
return new ResponseWrapper(ApplicationContextutil.getBean(getMapper(), BaseMapper.class).selectOne(IController.wrapper(map)));
}
@GetMapping(value = "/_find")
public ResponseWrapper find(@RequestParam Map<String,Object> map){
return new ResponseWrapper(ApplicationContextutil.getBean(getMapper(), BaseMapper.class).selectList(IController.wrapper(map)));
}
@GetMapping(value = "/_page")
public ResponseWrapper page(@PageableDefault Page page, @RequestParam Map<String,Object> map){
return new ResponseWrapper( ApplicationContextutil.getBean(getMapper(), BaseMapper.class).selectPage(IController.pageInit(page), IController.wrapper(map)));
}
}
MybatisPlus 实体映射库表
<!-- 实体映射库表 -->
<dependency>
<groupId>com.gitee.sunchenbin.mybatis.actable</groupId>
<artifactId>mybatis-enhance-actable</artifactId>
<version>1.5.0.RELEASE</version>
</dependency>
#create 系统启动后,会将所有的表删除掉,然后根据model中配置的结构重新建表,该操作会破坏原有数据。
#update 系统会自动判断哪些表是新建的,哪些字段要修改类型等,哪些字段要删除,哪些字段要新增,该操作不会破坏原有数据。
#none 系统不做任何处理。
#add 新增表/新增字段/新增索引/新增唯一约束的功能,不做做修改和删除 (只在版本1.0.9.RELEASE及以上支持)。
mybatis.table.auto=none
# 扫描用于创建表的对象的包名,多个包用“,”隔开
mybatis.model.pack=com.gs.game.model.*
# 数据库类型
mybatis.database.type=mysql
# xml 扫描路径
mybatis-plus.mapper-locations=classpath*:xxxx/*.xml,classpath*:com/gitee/sunchenbin/mybatis/actable/mapping/*/*.xml
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component
// 配置项
@PropertySource({"classpath:config/mybatis-auto.properties"})
// actable dao 包路径
@MapperScan({"com.gitee.sunchenbin.mybatis.actable.dao.*"} )
// manager包路径
@ComponentScan("com.gitee.sunchenbin.mybatis.actable.manager.*")
public class MybatisAutoConfig {
}
MyBatisPlus 逆向工程
<!-- mybatisPlus 逆向工程 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.3.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import java.util.Scanner;
public class GeneratorCodeConfig {
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 + "!");
}
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
// 都是做好事的 叫我 雷锋就行
gc.setAuthor("Lei Feng");
gc.setOpen(false);
//实体属性 Swagger2 注解
gc.setSwagger2(false);
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://127.0.0.1:3306/game_dev?useUnicode=true&characterEncoding=utf8&useSSL=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("123456");
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
//pc.setModuleName(scanner("模块名"));
pc.setParent("com.gs.game");
pc.setEntity("model.admin");
pc.setMapper("mapper.admin");
pc.setService("service.admin");
pc.setServiceImpl("service.admin.impl");
pc.setController("controller.admin");
mpg.setPackageInfo(pc);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
// 配置自定义输出模板
//指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
// templateConfig.setEntity("templates/entity2.java");
// templateConfig.setService();
// templateConfig.setController();
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setSuperEntityClass("com.baomidou.mybatisplus.extension.activerecord.Model");
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
strategy.setEntityLombokModel(true);
// 公共实体父类
strategy.setSuperEntityClass("com.gs.game.model.base.BaseEntity");
// 公共控制器父类
strategy.setSuperControllerClass("com.gs.game.controller.IController");
// 写于父类中的公共字段
// strategy.setSuperEntityColumns("id");
strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}
BaseEntity 基础实体类
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.gitee.sunchenbin.mybatis.actable.annotation.Column;
import com.gitee.sunchenbin.mybatis.actable.constants.MySqlTypeConstant;
import lombok.Data;
import java.io.Serializable;
import java.time.Instant;
@Data
public class BaseEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Column(isKey = true,comment = "主键")
private String id;
@Column(comment = "数据状态", defaultValue = "1")
private Integer state;
@Column(comment = "备注",length = 512)
private String remark;
@Column(comment = "版本号")
private Integer version;
@Column(comment = "创建用户")
@TableField(fill = FieldFill.INSERT)
private String createdBy;
@Column(comment = "创建时间",type = MySqlTypeConstant.DATETIME)
@TableField(fill = FieldFill.INSERT)
private Instant createdDate;
@Column(comment = "修改用户")
@TableField(fill = FieldFill.UPDATE)
private String lastModifiedBy;
@Column(comment = "修改时间",type = MySqlTypeConstant.DATETIME)
@TableField(fill = FieldFill.UPDATE)
private Instant lastModifiedDate;
}
icTest.http IController 测试文件
#其他类方法只需要替换 game/info 路由即可
### insert测试方法
PUT http://127.0.0.1:8787/game/info/_insert
Content-type: application/json;charset=UTF-8
token: 01e08bc338f14e4289a7a77fabdcbe28
{
"gameName":"QQ斗地主",
"createdDate": "2020-08-08"
}
### save测试方法
PUT http://127.0.0.1:8787/game/info/_save
Content-type: application/json;charset=UTF-8
{
"id": "1427449583447601153",
"gameName":"穿越火线"
}
### UPDATE 方法测试 url参数 body 修改的值
PUT http://127.0.0.1:8787/game/info/_update?gameName=穿越火线
Content-type: application/json;charset=UTF-8
{
"gameType": 2
}
### GET ONE findOne 方法测试
GET http://127.0.0.1:8787/game/info/_findOne?gameName=穿越火线
### GET LIST find方法测试
GET http://127.0.0.1:8787/game/info/_find
token: 3c8dcd0a127f4c028fb2ccb2d3c7ad7f
### GET LIST find方法测试
GET http://127.0.0.1:8787/game/info/_find?orderBy[0].column=gameName&orderBy[0].asc=false&orderBy[1].column=gameType&orderBy[1].asc=false
token: 3c8dcd0a127f4c028fb2ccb2d3c7ad7f
### GET 分页方法测试
GET http://127.0.0.1:8787/game/info/_page?current=1&size=999&orderBy[0].column=gameName&orderBy[0].asc=false&orderBy[1].column=gameType
token: 3c8dcd0a127f4c028fb2ccb2d3c7ad7f
### DELETE 方法测试
DELETE http://127.0.0.1:8787/game/info/_delete
Content-type: application/json;charset=UTF-8
{
}
### DELETE by ID 方法测试
DELETE http://127.0.0.1:8787/game/info/_deleteById?id=1427449583447601153
###
mcTest.http MyController 测试文件
### insert测试方法
PUT http://127.0.0.1:8787/game/my/_insert
Content-type: application/json;charset=UTF-8
token: 00b8d34f53be496b8ae4147db1b6c57a
entity: admin.GameInfo
{
"gameName":"晚间测试"
}
###
PUT http://127.0.0.1:8787/game/my/_save
Content-type: application/json;charset=UTF-8
token: 00b8d34f53be496b8ae4147db1b6c57a
entity: admin.GameInfo
{
"gameName":"QQ飞车"
}
### UPDATE 方法测试 url参数 body 修改的值
PUT http://127.0.0.1:8787/game/my/_update?gameName=王者荣耀
Content-type: application/json;charset=UTF-8
token: 00b8d34f53be496b8ae4147db1b6c57a
entity: admin.GameInfo
{
"gameType": 2
}
### GET ONE findOne 方法测试
GET http://127.0.0.1:8787/game/my/_findOne?gameName=QQ飞车
token: 00b8d34f53be496b8ae4147db1b6c57a
entity: admin.GameInfo
### GET LIST find方法测试
GET http://127.0.0.1:8787/game/my/_find
token: 00b8d34f53be496b8ae4147db1b6c57a
entity: admin.GameInfo
### GET LIST find方法测试
GET http://127.0.0.1:8787/game/my/_find?orderBy[0].column=gameName&orderBy[0].asc=false&orderBy[1].column=gameType&orderBy[1].asc=false
token: 00b8d34f53be496b8ae4147db1b6c57a
entity: admin.GameInfo
### GET 分页方法测试
GET http://127.0.0.1:8787/game/my/_page?current=1&size=999&orderBy[0].column=gameName&orderBy[0].asc=false&orderBy[1].column=gameType
token: 00b8d34f53be496b8ae4147db1b6c57a
entity: admin.GameInfo
### DELETE 方法测试
DELETE http://127.0.0.1:8787/game/my/_delete
Content-type: application/json;charset=UTF-8
token: 00b8d34f53be496b8ae4147db1b6c57a
entity: admin.GameInfo
{
"gameName": "QQ飞车"
}
### DELETE by ID 方法测试
DELETE http://127.0.0.1:8787/game/my/_deleteById?id=142968519276969574
token: 00b8d34f53be496b8ae4147db1b6c57a
entity: admin.GameInfo
###
新增、修改数据自动填充配置
@Component
public class DataAutoFill implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
this.strictInsertFill(metaObject, "createdBy", String.class, "SYSTEM");
this.strictInsertFill(metaObject, "createdDate", Instant.class, Instant.now());
}
@Override
public void updateFill(MetaObject metaObject) {
this.strictUpdateFill(metaObject, "lastModifiedBy", String.class, "SYSTEM");
this.strictUpdateFill(metaObject, "lastModifiedDate", Instant.class, Instant.now());
}
}
MybatisPlus 乐观锁 分页插件
@Configuration
public class MybatisPlusConfig {
/**
* 乐观锁插件
*
* 默认不开启 开启需要在实体中重写 version 字段 加上对应字段注解
* @Version
* private Integer version;
* @return
*/
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
}
/**
* 分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
//paginationInterceptor.setDialectType("mysql");
return paginationInterceptor;
}
}
时间格式统一处理
@Configuration
public class JacksonConfig {
@Bean
public ObjectMapper serializingObjectMapper() {
String formatValue = "yyyy-MM-dd HH:mm:ss";
DateTimeFormatter format = DateTimeFormatter.ofPattern(formatValue);
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(format));
//Instant 添加序列化程序
javaTimeModule.addSerializer(Instant.class, new JsonSerializer<Instant>() {
@Override
public void serialize(Instant instant, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
if (instant == null) {
return;
}
String jsonValue = format.format(instant.atZone(ZoneId.systemDefault()));
jsonGenerator.writeString(jsonValue);
}
});
// Instant 添加反序列化程序
javaTimeModule.addDeserializer(Instant.class, new JsonDeserializer<Instant>() {
@Override
public Instant deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
String dateString = jsonParser.getText().trim();
if(StringUtils.isNotBlank(dateString)){
Date pareDate;
try {
pareDate = DateFormatUtil.pareDate(dateString);
if(null != pareDate){
return pareDate.toInstant();
}
} catch (ParseException e) {
e.printStackTrace();
}
}
return null;
}
});
// Date 添加序列化程序
javaTimeModule.addSerializer(Date.class, new DateSerializer(false, new SimpleDateFormat(formatValue)));
// Date 添加反序列化程序
javaTimeModule.addDeserializer(Date.class, new JsonDeserializer<Date>() {
@Override
public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
String dateString = jsonParser.getText().trim();
if(StringUtils.isNotBlank(dateString)){
try {
return DateFormatUtil.pareDate(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
}
return null;
}
});
// 枚举序列化
javaTimeModule.addSerializer(Enum.class, new JsonSerializer<Enum>() {
@Override
public void serialize(Enum value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
// 必须配置项
gen.writeStartObject();
// 获取 枚举类 class
Class<?> lass = value.getClass();
List<Field> fileIds = new ArrayList<>();
// 拿所有字段
while (lass != null && ! lass.getName().equals("java.lang.Object")) {
Field[] fields = lass.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
fileIds.add(fields[i]);
}
lass = lass.getSuperclass();
}
// 字段循环赋值
for (Field fieId : fileIds){
fieId.setAccessible(true);
try {
if(! Modifier.isStatic(fieId.getModifiers()) ){
gen.writeObjectField(fieId.getName(),fieId.get(value));
}
}catch (Exception e){
}
}
gen.writeEndObject();
}
});
ObjectMapper mapper = new ObjectMapper()
.registerModule(new ParameterNamesModule())
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.registerModule(javaTimeModule);
return mapper;
}
}
全局异常处理
@ControllerAdvice
public class ExceptionHandler {
@ResponseBody
@ExceptionHandler(value = BusinessException.class)
public ResponseEntity businessExceptionHandler(HttpServletRequest httpServletRequest, BusinessException e) {
return new ResponseEntity<>(new ResponseWrapper(e.getCode(), e.getMsg()), HttpStatus.OK);
}
}