| 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.*; | 
|   | 
| 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 String BASE_FIELD_SET_PRIMARY_KEY_FUNTION_NAME = "setId"; | 
|   | 
|     /** | 
|      * 拦截逻辑实现 | 
|      * @param invocation 代理 | 
|      * @return Object | 
|      * @throws Throwable 异常 | 
|      */ | 
|     public Object intercept(Invocation invocation) throws Throwable { | 
|         MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[MAPPED_STATEMENT_INDEX]; | 
|         SqlCommandType commandType = mappedStatement.getSqlCommandType(); | 
|         if (commandType.equals(SqlCommandType.INSERT)) { | 
|             Object entity = invocation.getArgs()[PARAMETER_INDEX]; | 
|             if (entity instanceof BaseEntity) { | 
|                 Class<?> entityClass = entity.getClass(); | 
|                 Method setIdMt = null ; | 
|                 try{ | 
|                     setIdMt = entityClass.getMethod(BASE_FIELD_SET_PRIMARY_KEY_FUNTION_NAME, Long.class) ; | 
|                 }catch (Exception e){ | 
|                     //当entityClass没有setId方法时,会抛出异常 | 
|                 } | 
|                 if(setIdMt != null){ | 
|                     setIdMt.invoke(entity, new IDLongGenerator().generate()); | 
|                 } | 
|   | 
|                 invocation.getArgs()[PARAMETER_INDEX] = entity; | 
|             } | 
|         } | 
|         return invocation.proceed(); | 
|     } | 
|   | 
|     public Object plugin(Object target) { | 
|         return Plugin.wrap(target, this); | 
|     } | 
|   | 
| } |