mybatis实现公共字段填充

@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) {
 }
}

你可能感兴趣的:(数据库)