feat: 用mybatis的typehandler映射json,减少冗余代码和提升可读性

This commit is contained in:
Gadfly 2021-08-12 19:02:25 +08:00
parent 2a51b1bc25
commit 03c1c4f6a1
8 changed files with 208 additions and 21 deletions

View File

@ -14,7 +14,7 @@ public class SpuDTO {
private Long price;
private Integer sales;
private String pic;
private List<String> pics;
private String[] pics;
private String unit;
private String description;
private String detail;

View File

@ -25,7 +25,7 @@ public class PmsSpu extends BaseEntity {
private Long price;
private Integer sales;
private String pic;
private String pics;
private String[] pics;
private String unit;
private String description;
private String detail;

View File

@ -55,10 +55,6 @@ public class PmsSpuServiceImpl extends ServiceImpl<PmsSpuMapper, PmsSpu> impleme
// spu保存
PmsSpu spu = new PmsSpu();
BeanUtil.copyProperties(SpuDTO, spu);
if (SpuDTO.getPics() != null) {
String picUrls = JSONUtil.toJsonStr(SpuDTO.getPics());
spu.setPics(picUrls);
}
this.save(spu);
// 属性保存
@ -89,12 +85,6 @@ public class PmsSpuServiceImpl extends ServiceImpl<PmsSpuMapper, PmsSpu> impleme
PmsSpu spu = this.getById(id);
BeanUtil.copyProperties(spu, spuDTO);
if (StrUtil.isNotBlank(spu.getPics())) {
// spu专辑图片转换处理 json字符串 -> List
List<String> pics = JSONUtil.toList(JSONUtil.parseArray(spu.getPics()), String.class);
spuDTO.setPics(pics);
}
// 属性
List<PmsSpuAttributeValue> attrs = iPmsSpuAttributeValueService.
list(new LambdaQueryWrapper<PmsSpuAttributeValue>().eq(PmsSpuAttributeValue::getSpuId, id));
@ -120,10 +110,6 @@ public class PmsSpuServiceImpl extends ServiceImpl<PmsSpuMapper, PmsSpu> impleme
// spu保存
PmsSpu spu = new PmsSpu();
BeanUtil.copyProperties(SpuDTO, spu);
if (SpuDTO.getPics() != null) {
String pics = JSONUtil.toJsonStr(SpuDTO.getPics());
spu.setPics(pics);
}
this.updateById(spu);
// 属性保存
@ -202,11 +188,6 @@ public class PmsSpuServiceImpl extends ServiceImpl<PmsSpuMapper, PmsSpu> impleme
PmsSpu spu = this.getById(spuId);
SpuDTO SpuDTO = new SpuDTO();
BeanUtil.copyProperties(spu, SpuDTO);
if (StrUtil.isNotBlank(spu.getPics())) {
// spu专辑图片转换处理 json字符串 -> List
List<String> pics = JSONUtil.toList(JSONUtil.parseArray(spu.getPics()), String.class);
SpuDTO.setPics(pics);
}
// 属性
List<PmsSpuAttributeValue> attrs = iPmsSpuAttributeValueService.list(
new LambdaQueryWrapper<PmsSpuAttributeValue>(

View File

@ -1,11 +1,17 @@
package com.youlai.common.mybatis.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.youlai.common.mybatis.handler.FieldFillHandler;
import com.youlai.common.mybatis.handler.IntegerArrayJsonTypeHandler;
import com.youlai.common.mybatis.handler.LongArrayJsonTypeHandler;
import com.youlai.common.mybatis.handler.StringArrayJsonTypeHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@ -26,6 +32,17 @@ public class MybatisPlusConfig {
return interceptor;
}
@Bean
public ConfigurationCustomizer configurationCustomizer() {
return configuration -> {
// 全局注册自定义TypeHandler
TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
typeHandlerRegistry.register(String[].class, JdbcType.OTHER, StringArrayJsonTypeHandler.class);
typeHandlerRegistry.register(Long[].class, JdbcType.OTHER, LongArrayJsonTypeHandler.class);
typeHandlerRegistry.register(Integer[].class, JdbcType.OTHER, IntegerArrayJsonTypeHandler.class);
};
}
/**
* 自动填充数据库创建人创建时间更新人更新时间
*/

View File

@ -0,0 +1,120 @@
package com.youlai.common.mybatis.handler;
import com.baomidou.mybatisplus.core.toolkit.ArrayUtils;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.springframework.util.StringUtils;
import java.lang.reflect.Array;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Objects;
/**
* 数组类型转换 json
* <p>
* 主要是用于对象数据 基础类型包装对象不建议用
* <a href="https://www.jianshu.com/p/ab832f3fe81c">https://www.jianshu.com/p/ab832f3fe81c</a>
*
* @author Gadfly
* @since 2021-06-30 15:20
*/
@Slf4j
@MappedJdbcTypes(value = {JdbcType.OTHER}, includeNullJdbcType = true)
public class ArrayObjectJsonTypeHandler<E> extends BaseTypeHandler<E[]> {
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final String STRING_JSON_ARRAY_EMPTY = "[]";
static {
// 未知字段忽略
MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// 不使用科学计数
MAPPER.configure(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN, true);
// null 值不输出(节省内存)
MAPPER.setDefaultPropertyInclusion(JsonInclude.Include.NON_NULL);
}
private final Class<E[]> type;
public ArrayObjectJsonTypeHandler(Class<E[]> type) {
Objects.requireNonNull(type);
this.type = type;
}
@Override
public void setNonNullParameter(PreparedStatement ps, int i, E[] parameter, JdbcType jdbcType) throws SQLException {
ps.setString(i, toJson(parameter));
}
@Override
public E[] getNullableResult(ResultSet rs, String columnName) throws SQLException {
return toObject(rs.getString(columnName), type);
}
@Override
public E[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return toObject(rs.getString(columnIndex), type);
}
@Override
public E[] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
return toObject(cs.getString(columnIndex), type);
}
/**
* object json
*
* @param obj 对象
* @return String json字符串
*/
private String toJson(E[] obj) {
if (ArrayUtils.isEmpty(obj)) {
return STRING_JSON_ARRAY_EMPTY;
}
try {
return MAPPER.writeValueAsString(obj);
} catch (JsonProcessingException e) {
throw new RuntimeException("mybatis column to json error,obj:" + Arrays.toString(obj), e);
}
}
/**
* 转换对象
*
* @param json json数据
* @param clazz
* @return E
*/
private E[] toObject(String json, Class<E[]> clazz) {
if (json == null) {
return null;
}
if (!StringUtils.hasText(json)) {
return newArray(clazz);
}
try {
return MAPPER.readValue(json, clazz);
} catch (JsonProcessingException e) {
log.error("mybatis column json to object error,json:{}", json, e);
return newArray(clazz);
}
}
@SuppressWarnings("unchecked")
private E[] newArray(Class<E[]> clazz) {
return (E[]) Array.newInstance(clazz.getComponentType(), 0);
}
}

View File

@ -0,0 +1,24 @@
package com.youlai.common.mybatis.handler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.springframework.stereotype.Component;
/**
* Integer 数组类型转换 json
* <a href="https://www.jianshu.com/p/ab832f3fe81c">https://www.jianshu.com/p/ab832f3fe81c</a>
*
* @author Gadfly
* @since 2021-06-30 15:19
*/
@Slf4j
@Component
@MappedTypes(value = {Integer[].class})
@MappedJdbcTypes(value = {JdbcType.VARCHAR}, includeNullJdbcType = true)
public class IntegerArrayJsonTypeHandler extends ArrayObjectJsonTypeHandler<Integer> {
public IntegerArrayJsonTypeHandler() {
super(Integer[].class);
}
}

View File

@ -0,0 +1,24 @@
package com.youlai.common.mybatis.handler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.springframework.stereotype.Component;
/**
* Long 数组类型转换 json
* <a href="https://www.jianshu.com/p/ab832f3fe81c">https://www.jianshu.com/p/ab832f3fe81c</a>
*
* @author Gadfly
* @since 2021-06-30 15:26
*/
@Slf4j
@Component
@MappedTypes(value = {Long[].class})
@MappedJdbcTypes(value = {JdbcType.OTHER}, includeNullJdbcType = true)
public class LongArrayJsonTypeHandler extends ArrayObjectJsonTypeHandler<Long> {
public LongArrayJsonTypeHandler() {
super(Long[].class);
}
}

View File

@ -0,0 +1,21 @@
package com.youlai.common.mybatis.handler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.springframework.stereotype.Component;
/**
* @author Gadfly
* @since 2021-06-30 15:27
*/
@Slf4j
@Component
@MappedTypes(value = {String[].class})
@MappedJdbcTypes(value = {JdbcType.OTHER}, includeNullJdbcType = true)
public class StringArrayJsonTypeHandler extends ArrayObjectJsonTypeHandler<String> {
public StringArrayJsonTypeHandler() {
super(String[].class);
}
}