|  |  |  | 
|---|
|  |  |  |  | 
|---|
|  |  |  | 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") | 
|---|
|  |  |  | /** | 
|---|
|  |  |  | * 拦截逻辑实现 | 
|---|
|  |  |  | * @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.INSERT.equals(SqlCommandType.INSERT)) { | 
|---|
|  |  |  | if (commandType.equals(SqlCommandType.INSERT)) { | 
|---|
|  |  |  | Object entity = invocation.getArgs()[PARAMETER_INDEX]; | 
|---|
|  |  |  | if (entity instanceof BaseEntity) { | 
|---|
|  |  |  | Class<? extends Object> entityClass = entity.getClass(); | 
|---|
|  |  |  | Method setMt = entityClass.getMethod(BASE_FIELD_SET_PRIMARY_KEY_FUNTION_NAME, Long.class) ; | 
|---|
|  |  |  | //Class<? extends Object> entityClass = entity.getClass(); | 
|---|
|  |  |  | Class<?> entityClass = entity.getClass(); | 
|---|
|  |  |  | Method setMt = null ; | 
|---|
|  |  |  | try{ | 
|---|
|  |  |  | //有一些实体没有id,例如中间表 | 
|---|
|  |  |  | setMt = entityClass.getMethod(BASE_FIELD_SET_PRIMARY_KEY_FUNTION_NAME, Long.class) ; | 
|---|
|  |  |  | }catch (Exception e){ | 
|---|
|  |  |  | //当entityClass没有setId方法时,会抛出异常 | 
|---|
|  |  |  | } | 
|---|
|  |  |  | if(setMt != null){ | 
|---|
|  |  |  | setMt.invoke(entity, new IDLongGenerator().generate()); | 
|---|
|  |  |  | } | 
|---|
|  |  |  |  | 
|---|
|  |  |  | invocation.getArgs()[PARAMETER_INDEX] = entity; | 
|---|
|  |  |  | } | 
|---|
|  |  |  | } | 
|---|