MyBatis 插件之攔截器(Interceptor)


參考 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;
    }
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM