参考 https://blog.csdn.net/weixin_39494923/article/details/91534658
//项目实际使用
package com.yueworldframework.core.mybatis; import com.yueworldframework.core.support.SessionHelper; 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.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeanUtils; import java.lang.reflect.Method; import java.util.Date; import java.util.Properties; /** * Created by wangbs */ @Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})}) public class AuditingInterceptor implements Interceptor { private static final Logger logger = LoggerFactory.getLogger(AuditingInterceptor.class); private Properties props = null; @Override public Object intercept(Invocation invocation) throws Throwable { MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0]; SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType(); if (invocation.getArgs()[1] instanceof Pojo) { Pojo parameter = (Pojo) invocation.getArgs()[1]; if (SqlCommandType.INSERT == sqlCommandType) { // 初始化主键ID Method initializeUUID = BeanUtils.findDeclaredMethod(parameter.getClass(), "initializeUUID"); if (null != initializeUUID) { initializeUUID.invoke(parameter); } if(null==parameter.getCreator()){ parameter.setCreator(SessionHelper.getId()); } parameter.setUpdater(SessionHelper.getId()); parameter.setCreatedDate(new Date()); parameter.setUpdatedDate(parameter.getCreatedDate()); parameter.setVersion(1); } else if (SqlCommandType.UPDATE == sqlCommandType) { parameter.setUpdater(SessionHelper.getId()); parameter.setUpdatedDate(new Date()); parameter.setVersion(parameter.getVersion() + 1); } } return invocation.proceed(); } @Override public Object plugin(Object target) { if (target instanceof Executor) { return Plugin.wrap(target, this); } else { return target; } } public void setProperties(Properties properties) { if (null != properties && !properties.isEmpty()) props = properties; } }
原文地址:https://www.cnblogs.com/xiaowangbangzhu/p/11670657.html
时间: 2024-11-03 20:56:45