完整代码如下,方便同问者参考
public class UpdateDaoInterceptor implements DaoInterceptor {
private Logger logger = Logger.getLogger(getClass());
@Override
public void filter(DaoInterceptorChain chain) throws DaoException {
DaoStatement st = chain.getDaoStatement();
if (st instanceof NutPojo) {
// 如果是dao.insert(user)之类的操作,会进入这个分支
// 获取当前操作的对象
Object obj = ((NutPojo) st).getOperatingObject();
// 操作对象为null的时候跳过此拦截器
if (obj == null) {
chain.doChain();
return;
}
String methodRts = "setRts";
Method rtsMethod = hasMethod(obj, methodRts);
try {
if (rtsMethod != null)
rtsMethod.invoke(obj, DateUtils.getTimeMillis());
if (st.isUpdate()) {
// 更新操作
logger.debug("拦截到update操作。");
String modifyTime = "setModifyTime";
Method modifyTimeMethod = hasMethod(obj, modifyTime);
if (modifyTimeMethod != null)
modifyTimeMethod.invoke(obj, DateUtils.date());
} else if (st.isInsert()) {
// 新增操作
logger.debug("拦截到insert操作。");
String createTime = "setCreateTime";
Method createTimeMethod = hasMethod(obj, createTime);
if (createTimeMethod != null)
createTimeMethod.invoke(obj, DateUtils.date());
}
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
} else {
// 如果是自定义SQL,会进入这个分支
}
chain.doChain();// 继续下一个拦截器执行
}
private Method hasMethod(Object obj, String methodName) {
Class<? extends Object> clas = obj.getClass();
Method[] methods = clas.getDeclaredMethods();
if (methods != null && methods.length > 0) {
for (Method m : methods) {
String mName = m.getName();
if (methodName.equals(mName)) {
return m;
}
}
}
return null;
}
}