热数据处理 - Base基础类设置

v1.4.1
Parker 5 years ago
parent 26a445dc62
commit b4e494cfcc

@ -3,9 +3,10 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent> <parent>
<artifactId>opsli-boot-parent</artifactId> <artifactId>opsli-base-support</artifactId>
<groupId>org.opsliframework.boot</groupId> <groupId>org.opsliframework.boot</groupId>
<version>1.0.0</version> <version>1.0.0</version>
<relativePath>../pom.xml</relativePath>
</parent> </parent>
@ -25,6 +26,13 @@
<version>${version}</version> <version>${version}</version>
</dependency> </dependency>
<!-- 引入API模块 -->
<dependency>
<groupId>org.opsliframework.boot</groupId>
<artifactId>opsli-api</artifactId>
<version>${version}</version>
</dependency>
<!-- 引入Redis插件 --> <!-- 引入Redis插件 -->
<dependency> <dependency>
<groupId>org.opsliframework.boot</groupId> <groupId>org.opsliframework.boot</groupId>
@ -39,7 +47,6 @@
<version>${plugins.version}</version> <version>${plugins.version}</version>
</dependency> </dependency>
</dependencies> </dependencies>
</project> </project>

@ -7,10 +7,10 @@ import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature; import org.aspectj.lang.reflect.MethodSignature;
import org.opsli.api.base.warpper.ApiWrapper;
import org.opsli.common.annotation.EnableHotData; import org.opsli.common.annotation.EnableHotData;
import org.opsli.common.annotation.HotDataDel; import org.opsli.common.annotation.HotDataDel;
import org.opsli.common.annotation.HotDataPut; import org.opsli.common.annotation.HotDataPut;
import org.opsli.core.base.entity.BaseEntity;
import org.opsli.common.constants.CacheConstants; import org.opsli.common.constants.CacheConstants;
import org.opsli.core.cache.local.CacheUtil; import org.opsli.core.cache.local.CacheUtil;
import org.opsli.core.cache.pushsub.entity.CacheDataEntity; import org.opsli.core.cache.pushsub.entity.CacheDataEntity;
@ -71,27 +71,28 @@ public class CacheDataAop {
return returnValue; return returnValue;
} }
// ====== 如果 使用了 EnableHotData ,表示开启热数据加载 则执行下段代码 // ====== 如果 使用了 EnableHotData ,表示开启热数据加载 则执行下段代码
CacheDataEntity cacheDataEntity = this.putHandlerData(point, returnValue); CacheDataEntity cacheDataEntity = this.putHandlerData(point, returnValue);
if(cacheDataEntity != null){ if(cacheDataEntity == null){
// 更新缓存数据 return returnValue;
// 热点数据 }
if(CacheConstants.HOT_DATA.equals(cacheDataEntity.getCacheName())){
CacheUtil.putByKeyOriginal(cacheDataEntity.getKey(), returnValue);
}
// 永久数据
else if(CacheConstants.EDEN_DATA.equals(cacheDataEntity.getCacheName())) {
CacheUtil.putEdenByKeyOriginal(cacheDataEntity.getKey(), returnValue);
}
// 广播缓存数据 - 通知其他服务器同步数据 // 更新缓存数据
redisPlugin.sendMessage( // 热点数据
CacheDataMsgFactory.createMsg(cacheDataEntity.getType(), if(CacheConstants.HOT_DATA.equals(cacheDataEntity.getCacheName())){
cacheDataEntity.getKey(), returnValue, CacheType.UPDATE) CacheUtil.putByKeyOriginal(cacheDataEntity.getKey(), returnValue);
); }
// 永久数据
else if(CacheConstants.EDEN_DATA.equals(cacheDataEntity.getCacheName())) {
CacheUtil.putEdenByKeyOriginal(cacheDataEntity.getKey(), returnValue);
} }
// 广播缓存数据 - 通知其他服务器同步数据
redisPlugin.sendMessage(
CacheDataMsgFactory.createMsg(cacheDataEntity.getType(),
cacheDataEntity.getKey(), returnValue, CacheType.UPDATE)
);
return returnValue; return returnValue;
} }
@ -114,17 +115,19 @@ public class CacheDataAop {
// ====== 如果 使用了 EnableHotData ,表示开启热数据加载 则执行下段代码 // ====== 如果 使用了 EnableHotData ,表示开启热数据加载 则执行下段代码
List<CacheDataEntity> cacheDataEntityList = this.delHandlerData(point, args); List<CacheDataEntity> cacheDataEntityList = this.delHandlerData(point, args);
if(cacheDataEntityList != null && cacheDataEntityList.size() > 0){ if(cacheDataEntityList == null || cacheDataEntityList.size() == 0){
for (CacheDataEntity cacheDataEntity : cacheDataEntityList) { return returnValue;
// 更新缓存数据 - 删除缓存 }
CacheUtil.del(cacheDataEntity.getKey());
for (CacheDataEntity cacheDataEntity : cacheDataEntityList) {
// 广播缓存数据 - 通知其他服务器同步数据 // 更新缓存数据 - 删除缓存
redisPlugin.sendMessage( CacheUtil.del(cacheDataEntity.getKey());
CacheDataMsgFactory.createMsg(cacheDataEntity.getType(),
cacheDataEntity.getKey(), returnValue, CacheType.DELETE) // 广播缓存数据 - 通知其他服务器同步数据
); redisPlugin.sendMessage(
} CacheDataMsgFactory.createMsg(cacheDataEntity.getType(),
cacheDataEntity.getKey(), returnValue, CacheType.DELETE)
);
} }
return returnValue; return returnValue;
@ -144,8 +147,8 @@ public class CacheDataAop {
if(returnValue == null){ if(returnValue == null){
return null; return null;
} }
// 这里 只对 继承了 BaseEntity 的类做处理 // 这里 只对 继承了 ApiWrapper 的类做处理
if(!(returnValue instanceof BaseEntity)){ if(!(returnValue instanceof ApiWrapper)){
return null; return null;
} }
// 报错不处理 // 报错不处理
@ -177,10 +180,10 @@ public class CacheDataAop {
try { try {
// 这里 只对 继承了 BaseEntity 的类做处理 // 这里 只对 继承了 BaseEntity 的类做处理
BaseEntity baseEntity = (BaseEntity) returnValue; ApiWrapper apiWrapper = (ApiWrapper) returnValue;
// key 存储ID // key 存储ID
String key = keyBuf.append(baseEntity.getId()).toString(); String key = keyBuf.append(apiWrapper.getId()).toString();
ret = new CacheDataEntity(); ret = new CacheDataEntity();
ret.setKey(key); ret.setKey(key);
@ -261,10 +264,10 @@ public class CacheDataAop {
ret.setCacheName(aCache.name()); ret.setCacheName(aCache.name());
cacheDataEntities.add(ret); cacheDataEntities.add(ret);
} }
} else if (arg instanceof BaseEntity) { } else if (arg instanceof ApiWrapper) {
// key 存储ID // key 存储ID
BaseEntity baseEntity = (BaseEntity) arg; ApiWrapper apiWrapper = (ApiWrapper) arg;
String key = keyBuf.toString() + baseEntity.getId(); String key = keyBuf.toString() + apiWrapper.getId();
CacheDataEntity ret = new CacheDataEntity(); CacheDataEntity ret = new CacheDataEntity();
ret.setKey(key); ret.setKey(key);
ret.setType(type); ret.setType(type);
@ -272,8 +275,8 @@ public class CacheDataAop {
cacheDataEntities.add(ret); cacheDataEntities.add(ret);
} else if (arg instanceof Collection) { } else if (arg instanceof Collection) {
try { try {
Collection<BaseEntity> baseEntityList = (Collection<BaseEntity>) arg; Collection<ApiWrapper> baseEntityList = (Collection<ApiWrapper>) arg;
for (BaseEntity baseEntity : baseEntityList) { for (ApiWrapper baseEntity : baseEntityList) {
// key 存储ID // key 存储ID
String key = keyBuf.toString() + baseEntity.getId(); String key = keyBuf.toString() + baseEntity.getId();
CacheDataEntity ret = new CacheDataEntity(); CacheDataEntity ret = new CacheDataEntity();

@ -0,0 +1,82 @@
package org.opsli.core.aspect;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.opsli.common.exception.ServiceException;
import org.opsli.core.msg.CoreMsg;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import static org.opsli.common.constants.OrderConstants.SQL_ORDER;
/**
* SQL
*
* @author parker
* @date 2020-09-16
*/
@Slf4j
@Order(SQL_ORDER)
@Aspect
@Component
public class SQLDataAop {
@Pointcut("execution(public * org.opsli.core.base.service.impl.CrudServiceImpl.insert(..))")
public void insert() {
}
@Pointcut("execution(public * org.opsli.core.base.service.impl.CrudServiceImpl.update*(..))")
public void update() {
}
@Pointcut("execution(public * org.opsli.core.base.service.impl.CrudServiceImpl.delete*(..))")
public void delete() {
}
@AfterReturning(returning = "ret", pointcut = "insert()")
public void insertHadnler(Object ret){
try {
if(ret == null){
throw new ServiceException(CoreMsg.SQL_EXCEPTION_UPDATE);
}
} catch (ServiceException e) {
throw e;
} catch (Throwable e) {
log.error(e.getMessage(),e);
}
}
@AfterReturning(returning = "ret", pointcut = "update()")
public void updateHadnler(Object ret){
try {
if(ret == null){
throw new ServiceException(CoreMsg.SQL_EXCEPTION_UPDATE);
}
} catch (ServiceException e) {
throw e;
} catch (Throwable e) {
log.error(e.getMessage(),e);
}
}
@AfterReturning(returning = "ret", pointcut = "delete()")
public void deleteHadnler(Object ret){
try {
if(ret != null){
Integer retCount = (Integer) ret;
if(retCount == 0){
throw new ServiceException(CoreMsg.SQL_EXCEPTION_DELETE);
}
}else{
throw new ServiceException(CoreMsg.SQL_EXCEPTION_DELETE);
}
} catch (ServiceException e) {
throw e;
} catch (Throwable e) {
log.error(e.getMessage(),e);
}
}
}

@ -3,9 +3,11 @@ package org.opsli.core.base.concroller;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.opsli.api.base.warpper.ApiWrapper;
import org.opsli.common.annotation.EnableHotData; import org.opsli.common.annotation.EnableHotData;
import org.opsli.common.exception.ServiceException; import org.opsli.common.exception.ServiceException;
import org.opsli.common.msg.CommonMsg; import org.opsli.common.msg.CommonMsg;
import org.opsli.common.utils.WrapperUtil;
import org.opsli.core.base.entity.BaseEntity; import org.opsli.core.base.entity.BaseEntity;
import org.opsli.core.base.service.interfaces.CrudServiceInterface; import org.opsli.core.base.service.interfaces.CrudServiceInterface;
import org.opsli.core.cache.local.CacheUtil; import org.opsli.core.cache.local.CacheUtil;
@ -15,7 +17,7 @@ import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
import java.lang.reflect.*; import java.lang.reflect.ParameterizedType;
/** /**
* @BelongsProject: opsli-boot * @BelongsProject: opsli-boot
@ -29,11 +31,13 @@ import java.lang.reflect.*;
*/ */
@Slf4j @Slf4j
@RestController @RestController
public abstract class BaseRestController <T extends BaseEntity, S extends CrudServiceInterface<T>>{ public abstract class BaseRestController <E extends ApiWrapper, T extends BaseEntity, S extends CrudServiceInterface<E,T>>{
/** 开启热点数据状态 */ /** 开启热点数据状态 */
protected boolean hotDataFlag = false; protected boolean hotDataFlag = false;
/** Model Clazz 类 */
protected Class<E> modelClazz;
/** Entity Clazz 类 */ /** Entity Clazz 类 */
protected Class<T> entityClazz; protected Class<T> entityClazz;
@ -49,47 +53,45 @@ public abstract class BaseRestController <T extends BaseEntity, S extends CrudSe
* @return * @return
*/ */
@ModelAttribute @ModelAttribute
public T get(@RequestParam(required=false) String id) { public E get(@RequestParam(required=false) String id) {
T entity = null; E model = null;
if (StringUtils.isNotBlank(id)){ if (StringUtils.isNotBlank(id)){
// 如果开启缓存 先从缓存读 // 如果开启缓存 先从缓存读
if(hotDataFlag){ if(hotDataFlag){
entity = CacheUtil.get(id, entityClazz); model = WrapperUtil.transformInstance(
if(entity != null){ CacheUtil.get(id, entityClazz),modelClazz);
return entity; if(model != null){
return model;
} }
} }
// 如果缓存没读到 则去数据库读 // 如果缓存没读到 则去数据库读
entity = IService.get(id); model = WrapperUtil.transformInstance(IService.get(id),modelClazz);
if(entity != null){ if(model != null){
// 如果开启缓存 将数据库查询对象 存如缓存 // 如果开启缓存 将数据库查询对象 存如缓存
if(hotDataFlag){ if(hotDataFlag){
CacheUtil.put(id, entity); CacheUtil.put(id, model);
} }
} }
} }
if (entity == null){ if (model == null){
try { try {
// 创建泛型对象 // 创建泛型对象
entity = this.createModel(); model = this.createModel();
}catch (Exception e){ }catch (Exception e){
log.error(CommonMsg.EXCEPTION_CONTROLLER_MODEL.toString()+" : {}",e.getMessage()); log.error(CommonMsg.EXCEPTION_CONTROLLER_MODEL.toString()+" : {}",e.getMessage());
throw new ServiceException(CommonMsg.EXCEPTION_CONTROLLER_MODEL); throw new ServiceException(CommonMsg.EXCEPTION_CONTROLLER_MODEL);
} }
} }
return entity; return model;
} }
// ================================================= // =================================================
@PostConstruct @PostConstruct
public void init(){ public void init(){
try { try {
this.entityClazz = this.getModelClass(); this.modelClazz = this.getModelClass();
this.entityClazz = this.getEntityClass();
Class<?> serviceClazz = IService.getServiceClazz(); Class<?> serviceClazz = IService.getServiceClazz();
// 判断是否开启热点数据 // 判断是否开启热点数据
if(serviceClazz != null){ if(serviceClazz != null){
@ -106,12 +108,12 @@ public abstract class BaseRestController <T extends BaseEntity, S extends CrudSe
/** /**
* *
* @return * @return
*/ */
private T createModel() { private E createModel() {
try { try {
Class<T> modelClazz = this.entityClazz; Class<E> modelClazz = this.modelClazz;
return modelClazz.newInstance(); return modelClazz.newInstance();
} catch (Exception e) { } catch (Exception e) {
log.error(e.getMessage(),e); log.error(e.getMessage(),e);
@ -119,12 +121,22 @@ public abstract class BaseRestController <T extends BaseEntity, S extends CrudSe
return null; return null;
} }
/**
* Clazz
* @return
*/
private Class<E> getModelClass(){
Class<E> tClass = (Class<E>)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];
return tClass;
}
/** /**
* Clazz * Clazz
* @return * @return
*/ */
private Class<T> getModelClass(){ private Class<T> getEntityClass(){
Class<T> tClass = (Class<T>)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0]; Class<T> tClass = (Class<T>)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[1];
return tClass; return tClass;
} }

@ -0,0 +1,38 @@
package org.opsli.core.base.entity;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import org.opsli.api.base.warpper.ApiWrapper;
/**
*
* Entity
*
* @author Parker
* @date 2019-05-11
*
*/
@Data
@Accessors(chain = true)
@EqualsAndHashCode(callSuper = false)
public abstract class BaseEntity extends ApiWrapper {
private static final long serialVersionUID = 1L;
/** deleted @TableLogic
* deleted Char 0 1
*
* Entity deleted WrapperModel
* WrapperModel
* */
/**
@TableLogic
private Integer deleted;
**/
}

@ -0,0 +1,190 @@
package org.opsli.core.base.service.impl;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.opsli.api.base.warpper.ApiWrapper;
import org.opsli.common.annotation.EnableHotData;
import org.opsli.common.constants.MyBatisConstants;
import org.opsli.common.utils.WrapperUtil;
import org.opsli.core.base.entity.BaseEntity;
import org.opsli.core.base.service.base.BaseService;
import org.opsli.core.base.service.interfaces.CrudServiceInterface;
import javax.annotation.PostConstruct;
import java.lang.reflect.ParameterizedType;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
/**
* @BelongsProject: opsli-boot
* @BelongsPackage: org.opsli.common.base.service.impl
* @Author: Parker
* @CreateTime: 2020-09-14 17:31
* @Description: CurdServiceImpl -
*
*
*
*
*
* save
*
*/
@Slf4j
public abstract class CrudServiceImpl<M extends BaseMapper<T>, E extends ApiWrapper, T extends BaseEntity>
extends BaseService<M, T> implements CrudServiceInterface<E,T> {
/** entity Class 类 */
protected Class<T> entityClazz;
/** entity Class 类 */
protected Class<E> modelClazz;
@Override
public E get(String id) {
return transformT2M(
baseMapper.selectById(id)
);
}
@Override
public E get(E model) {
if(model == null) return null;
return transformT2M(
baseMapper.selectById(model.getId())
);
}
@Override
public E insert(E model) {
if(model == null) return null;
T entity = transformM2T(model);
int count = baseMapper.insert(entity);
if(count > 0){
return transformT2M(entity);
}
return null;
}
@Override
public E update(E model) {
if(model == null) return null;
T entity = transformM2T(model);
int count = baseMapper.updateById(entity);
if(count > 0){
return transformT2M(entity);
}
return null;
}
@Override
public int delete(String id) {
return baseMapper.deleteById(id);
}
@Override
public int delete(E model) {
if(model == null) return 0;
return baseMapper.deleteById(model.getId());
}
@Override
public int deleteAll(String[] ids) {
if(ids == null) return 0;
List<String> idList = Arrays.asList(ids);
return baseMapper.deleteBatchIds(idList);
}
@Override
public int deleteAll(Collection<E> models) {
if(models == null || models.isEmpty()) return 0;
List<String> idList = Lists.newArrayListWithCapacity(models.size());
for (E entity : models) {
idList.add(entity.getId());
}
return baseMapper.deleteBatchIds(idList);
}
@Override
public List<E> findList(E model) {
return null;
}
// ======================== 对象转化 ========================
/**
* entity model
* @param entity
* @return
*/
protected E transformT2M(T entity){
return WrapperUtil.transformInstance(entity, modelClazz);
}
/**
*
* entitys models
* @param entitys
* @return
*/
protected List<E> transformTs2Ms(List<T> entitys){
return WrapperUtil.transformInstance(entitys, modelClazz);
}
/**
* model entity
* @param model
* @return
*/
protected T transformM2T(E model){
return WrapperUtil.transformInstance(model, entityClazz);
}
/**
*
* models entitys
* @param models
* @return
*/
protected List<T> transformMs2Ts(List<E> models){
return WrapperUtil.transformInstance(models, entityClazz);
}
// ======================== 初始化 ========================
/**
*
*/
@PostConstruct
public void init(){
try {
this.modelClazz = this.getModelClass();
this.entityClazz = this.getEntityClass();
}catch (Exception e){
log.error(e.getMessage(),e);
}
}
/**
* Clazz
* @return
*/
private Class<E> getModelClass(){
Class<E> tClass = (Class<E>)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[1];
return tClass;
}
/**
* Clazz
* @return
*/
private Class<T> getEntityClass(){
Class<T> tClass = (Class<T>)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[2];
return tClass;
}
}

@ -0,0 +1,148 @@
package org.opsli.core.base.service.interfaces;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import java.util.Collection;
import java.util.List;
/**
*
*
* ===
*
*
*
*
*
*
* @param <E>
* @param <T>
*/
public interface CrudServiceInterface<E,T> extends BaseServiceInterface<T> {
/**
*
*
* @param id
* @return
*/
E get(String id);
/**
*
*
* @param model
* @return
*/
E get(E model);
/**
*
*
*
*
*
*
*
* @param model
* @return
*/
E insert(E model);
/**
*
*
*
*
*
*
*
* @param model
* @return
*/
E update(E model);
/**
*
*
*
*
*
*
*
* @param id
* @return
* @see int delete(T entity)
*/
int delete(String id);
/**
*
*
*
*
*
*
*
* @param model
* @return
*/
int delete(E model);
/**
*
*
*
*
*
*
*
* @param ids
* @return
*/
int deleteAll(String[] ids);
/**
*
*
*
*
*
*
*
* @param models
* @return
*/
int deleteAll(Collection<E> models);
/**
*
*
* @param model
* @return
*/
List<E> findList(E model);
/**
*
*
* @return
* @see List<E> findAllList(T entity)
*/
//Page findPage(Page page, T t);
}

@ -0,0 +1,44 @@
package org.opsli.core.conf;
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.opsli.core.conf.mybatis.AutoFillInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* @Author parker
*
* MyBatis - Plus
*
*/
@Slf4j
@EnableTransactionManagement //开启事务
@Configuration
public class MyBatisPlusConfig {
/***
*
* @return
*/
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor(){
return new OptimisticLockerInterceptor();
}
/**
* Mybatis
* @param sqlSessionFactory
* @return
*/
@Bean
public String myInterceptor(SqlSessionFactory sqlSessionFactory) {
sqlSessionFactory.getConfiguration().addInterceptor(new AutoFillInterceptor());
return "interceptor";
}
}

@ -0,0 +1,161 @@
package org.opsli.core.conf.mybatis;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ReflectUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.opsli.common.constants.MyBatisConstants;
import org.springframework.stereotype.Component;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
/**
* MyBatis
*
* PSPlus
*
* https://www.cnblogs.com/qingshan-tang/p/13299701.html
*/
@Component
@Slf4j
@Intercepts(@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}))
public class AutoFillInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws IllegalAccessException, InvocationTargetException {
fillField(invocation);
return invocation.proceed();
}
/**
*
* @param invocation
*/
private void fillField(Invocation invocation) {
Object[] args = invocation.getArgs();
SqlCommandType sqlCommandType = null;
for (int i = 0; i < args.length; i++) {
Object arg = args[i];
String className = arg.getClass().getName();
log.info(i + " 参数类型:" + className);
//第一个参数处理。根据它判断是否给“操作属性”赋值。
if (arg instanceof MappedStatement) {//如果是第一个参数 MappedStatement
MappedStatement ms = (MappedStatement) arg;
sqlCommandType = ms.getSqlCommandType();
log.info("操作类型:" + sqlCommandType);
if (sqlCommandType == SqlCommandType.INSERT || sqlCommandType == SqlCommandType.UPDATE) {//如果是“增加”或“更新”操作,则继续进行默认操作信息赋值。否则,则退出
continue;
} else {
break;
}
}
if (sqlCommandType == SqlCommandType.INSERT) {
// 新增
this.insertFill(arg);
} else if (sqlCommandType == SqlCommandType.UPDATE) {
// 修改
this.updateFill(arg);
}
}
}
/**
*
* @param arg
*/
public void insertFill(Object arg) {
Field[] fields = ReflectUtil.getFields(arg.getClass());
for (Field f : fields) {
f.setAccessible(true);
switch (f.getName()) {
// 创建人
case MyBatisConstants.FIELD_CREATE_BY:
setProperty(arg, MyBatisConstants.FIELD_CREATE_BY, "测试");
break;
// 创建日期
case MyBatisConstants.FIELD_CREATE_TIME:
setProperty(arg, MyBatisConstants.FIELD_CREATE_TIME, new Date());
break;
// 更新人
case MyBatisConstants.FIELD_UPDATE_BY:
setProperty(arg, MyBatisConstants.FIELD_UPDATE_BY, "测试");
break;
// 更新日期
case MyBatisConstants.FIELD_UPDATE_TIME:
setProperty(arg, MyBatisConstants.FIELD_UPDATE_TIME, new Date());
break;
// 乐观锁
case MyBatisConstants.FIELD_OPTIMISTIC_LOCK:
setProperty(arg, MyBatisConstants.FIELD_OPTIMISTIC_LOCK, 0);
break;
// 逻辑删除
case MyBatisConstants.FIELD_DELETE_LOGIC:
setProperty(arg, MyBatisConstants.FIELD_DELETE_LOGIC, MyBatisConstants.LOGIC_NOT_DELETE_VALUE);
break;
default:
break;
}
f.setAccessible(false);
}
}
/**
*
* @param arg
*/
public void updateFill(Object arg) {
/**
* TODO
*
*
*
*/
Field[] fields = ReflectUtil.getFields(arg.getClass());
for (Field f : fields) {
f.setAccessible(true);
switch (f.getName()) {
// 更新人
case MyBatisConstants.FIELD_UPDATE_BY:
setProperty(arg, MyBatisConstants.FIELD_UPDATE_BY, "测试修改");
break;
// 更新日期
case MyBatisConstants.FIELD_UPDATE_TIME:
setProperty(arg, MyBatisConstants.FIELD_UPDATE_TIME, new Date());
break;
default:
break;
}
f.setAccessible(false);
}
}
// =======================================
/**
*
*
* @param bean
*/
private void setProperty(Object bean, String name, Object value) {
//根据需要,将相关属性赋上默认值
BeanUtil.setProperty(bean, name, value);
}
@Override
public Object plugin(Object o) {
return Plugin.wrap(o, this);
}
@Override
public void setProperties(Properties properties) {
}
}

@ -1,7 +1,7 @@
package org.opsli.core.handler; package org.opsli.core.handler;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.opsli.common.api.ResultVo; import org.opsli.api.base.result.ResultVo;
import org.opsli.common.exception.EmptyException; import org.opsli.common.exception.EmptyException;
import org.opsli.common.exception.ServiceException; import org.opsli.common.exception.ServiceException;
import org.opsli.core.msg.CoreMsg; import org.opsli.core.msg.CoreMsg;
@ -70,7 +70,7 @@ public class GlobalExceptionHandler {
@ResponseBody @ResponseBody
public ResultVo sqlIntegrityConstraintViolationException(EmptyException e) { public ResultVo sqlIntegrityConstraintViolationException(EmptyException e) {
log.error("数据异常:{}",e.getMessage(),e); log.error("数据异常:{}",e.getMessage(),e);
ResultVo errorR = ResultVo.error(CoreMsg.MySQL_EXCEPTION_SQL_INTEGRITY_CONSTRAINT_VIOLATION.getMessage()); ResultVo errorR = ResultVo.error(CoreMsg.SQL_EXCEPTION_INTEGRITY_CONSTRAINT_VIOLATION.getMessage());
errorR.setCode(e.getCode()); errorR.setCode(e.getCode());
return errorR; return errorR;
} }

@ -11,11 +11,11 @@ import org.opsli.common.base.msg.BaseMsg;
*/ */
public enum CoreMsg implements BaseMsg { public enum CoreMsg implements BaseMsg {
/** /** SQL */
* Mybatis-Plus SQL_EXCEPTION_UPDATE(10100,"更新数据失败,请稍后再次尝试!"),
*/ SQL_EXCEPTION_INSERT(10101,"新增数据失败,请稍后再次尝试!"),
/** Mybatis-Plus 乐观锁 */ SQL_EXCEPTION_DELETE(10102,"删除数据失败,请稍后再次尝试!"),
MYBATIS_OPTIMISTIC_LOCKER(10100,"当前数据已被更改,请刷新重试"), SQL_EXCEPTION_INTEGRITY_CONSTRAINT_VIOLATION(10105,"数据主键冲突或者已有该数据"),
/** /**
* Redis * Redis
@ -25,7 +25,7 @@ public enum CoreMsg implements BaseMsg {
/** /**
* MySQL * MySQL
*/ */
MySQL_EXCEPTION_SQL_INTEGRITY_CONSTRAINT_VIOLATION(10300,"数据主键冲突或者已有该数据!"),
; ;
Loading…
Cancel
Save