1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 | package com.nowfox.commons.plugin; import java.lang.reflect.Field; import java.util.Date; import java.util.Properties; 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 org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.nowfox.commons.util.IdUtils; /** * 通用数据库拦截器 * 没有设置id时设置id;插入时,如果没有创建时间补充;更新时间必补充 * * @author nowfox * */ @Intercepts ({ @Signature (type = Executor. class , method = "update" , args = { MappedStatement. class , Object. class }) }) public class CommonDbInterceptor implements Interceptor { private Logger logger = LoggerFactory.getLogger(getClass()); private final static String FIELD_ID = "id" ; private final static String FIELD_GMT_CREATE = "gmtCreate" ; private final static String FIELD_GMT_MODIFIED = "gmtModified" ; @SuppressWarnings ({ "rawtypes" }) @Override public Object intercept(Invocation invocation) throws Throwable { try { Object parameter = invocation.getArgs()[ 1 ]; Date now = new Date(); Class classParameter = (Class) parameter.getClass(); Field[] fields = classParameter.getDeclaredFields(); for (Field field : fields) { field.setAccessible( true ); String fieldName = field.getName(); if (FIELD_ID.equalsIgnoreCase(fieldName)) { Object value = field.get(parameter); if (value == null ) { field.set(parameter, IdUtils.getLongId()); } } else if (FIELD_GMT_CREATE.equalsIgnoreCase(fieldName)) { Object value = field.get(parameter); if (value == null ) { // gmtCreate只有插入才添加 MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[ 0 ]; SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType(); if (SqlCommandType.INSERT.equals(sqlCommandType)) { field.set(parameter, now); } } } else if (FIELD_GMT_MODIFIED.equalsIgnoreCase(fieldName)) { field.set(parameter, now); } } } catch (Exception e) { logger.error( "通用设置值时出错" , e); } return invocation.proceed(); } @Override public Object plugin(Object target) { return Plugin.wrap(target, this ); } @Override public void setProperties(Properties properties) { } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 | <? xml version = "1.0" encoding = "UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" < configuration > < settings > < setting name = "logPrefix" value = "dao." /> </ settings > < plugins > < plugin interceptor = "com.nowfox.commons.plugin.CommonDbInterceptor" > </ plugin > </ plugins > </ configuration > |