package com.dy.common.mybatis; import com.dy.common.po.BaseEntity; import com.dy.common.util.IDLongGenerator; import org.apache.ibatis.executor.Executor; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.mapping.SqlCommandType; import org.apache.ibatis.plugin.Interceptor; import org.apache.ibatis.plugin.Intercepts; import org.apache.ibatis.plugin.Invocation; import org.apache.ibatis.plugin.Plugin; import org.apache.ibatis.plugin.Signature; import java.lang.reflect.Method; @Intercepts( { @Signature( type = Executor.class, method = "update", args = { MappedStatement.class, Object.class } ) } ) public class AutoGenerateIdInterceptor implements Interceptor { static int MAPPED_STATEMENT_INDEX = 0; static int PARAMETER_INDEX = 1; static int ROWBOUNDS_INDEX = 2; static int RESULT_HANDLER_INDEX = 3; static String BASE_FIELD_SET_PRIMARY_KEY_FUNTION_NAME = "setId"; static String BASE_FIELD_SET_CREATE_TIME_FUNTION_NAME = "setCreateDt"; static String BASE_FIELD_SET_UPDATE_TIME_FUNTION_NAME = "setUpdateDt"; static String BASE_FIELD_SET_DELETE_FUNTION_NAME = "setDelete"; public AutoGenerateIdInterceptor() { //System.out.println("auto generate primaryKey mybatis plugin start!!!"); } @SuppressWarnings("static-access") public Object intercept(Invocation invocation) throws Throwable { MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[MAPPED_STATEMENT_INDEX]; SqlCommandType commandType = mappedStatement.getSqlCommandType(); if (commandType.INSERT.equals(SqlCommandType.INSERT)) { Object entity = invocation.getArgs()[PARAMETER_INDEX]; if (entity instanceof BaseEntity) { Class entityClass = entity.getClass(); Method setMt = entityClass.getMethod(BASE_FIELD_SET_PRIMARY_KEY_FUNTION_NAME, Long.class) ; if(setMt != null){ setMt.invoke(entity, new IDLongGenerator().generate()); } invocation.getArgs()[PARAMETER_INDEX] = entity; } } return invocation.proceed(); } public Object plugin(Object target) { return Plugin.wrap(target, this); } }