在表设计时,通常各个表有一些公共字段,比如主键、创建时间、最后修改时间等。这些字段如果都由开发人员去手动设置,一个是产生无用的代码,另外有可能规则不一致,造成错误。因此对于各个表的公用字段,一般会统一处理,MyBatis和Hibernate都有自身的拦截器,实现对应的接口,并配置即可。
本文以MyBatis为例说明。假设各个表都有3个公共字段:id、gmt_create、gmt_modified。
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) {
}
}
然后在mybatis-config.xml里指定拦截器
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="logPrefix" value="dao." />
</settings>
<plugins>
<plugin interceptor="com.nowfox.commons.plugin.CommonDbInterceptor">
</plugin>
</plugins>
</configuration>