因为 mp
只能在传入 Entity
的情况下自动填充字段。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| import cn.hutool.core.util.ReflectUtil; import com.baomidou.mybatisplus.core.conditions.AbstractWrapper; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Component;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap;
@Slf4j @Aspect @Component @RequiredArgsConstructor public class MybatisMetaAspect {
private final ConcurrentMap<Class<?>, Object> entityMap = new ConcurrentHashMap<>();
@Pointcut("execution(* com.baomidou.mybatisplus.core.mapper.BaseMapper.update(com.baomidou.mybatisplus.core.conditions.Wrapper))") public void update() { }
@Around("update()") public Object aroundUpdate(ProceedingJoinPoint pjp) { try { Object result = invoke(pjp); if (result != null) { return result; } return pjp.proceed(pjp.getArgs()); } catch (Throwable e) { log.error("mybatis around update error", e); } return null; }
private Object invoke(ProceedingJoinPoint pjp) { Object[] args = pjp.getArgs(); if (args == null || args.length != 1) { return null; } Object arg = args[0]; if (arg instanceof AbstractWrapper<?, ?, ?> wrapper) { Class<?> entityClass = wrapper.getEntityClass(); if (entityClass == null) { log.warn("Detected that the entity is empty, which will cause automatic filling to fail. Please use `new UpdateWrapper<>(new T())` or `new UpdateWrapper<>(T.class)` instead."); return null; } Object entity = entityMap.get(entityClass); if (entity == null) { entity = ReflectUtil.newInstance(entityClass); entityMap.put(entityClass, entity); } return ReflectUtil.invoke(pjp.getThis(), "update", entity, arg); } return null; }
}
|