mybatis自定义拦截器设置createBy&createTime

@Intercepts({
		@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
})
public class PrepareInterceptor implements Interceptor {
	@Autowired
	private OAuthUtils oAuthUtils;

	@Override
	public Object intercept(Invocation invocation) throws Throwable {
		MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
		Object object = invocation.getArgs()[1];
		// sql类型
		SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();

		UserInfo userInfo = oAuthUtils.getUserInfo();
		if (SqlCommandType.INSERT.equals(sqlCommandType)) {
			// 插入操作
			if (object instanceof DefaultSqlSession.StrictMap) {
				// FIXME 批量操作(还有没有别的方式判断?)
				Map map = (DefaultSqlSession.StrictMap) object;
				List list = (List) map.get("list");
				for (Object o : list) {
					reflectCreateInfo(o);
				}
			} else {
				// 单行
				reflectCreateInfo(object);
			}
		} else if (SqlCommandType.UPDATE.equals(sqlCommandType)) {
			// update操作
			if (object instanceof DefaultSqlSession.StrictMap) {
				// 多行
				Map map = (DefaultSqlSession.StrictMap) object;
				List list = (List) map.get("list");
				for (Object o : list) {
					reflectUpdateInfo(o);
				}
			} else {
				// 单行
				reflectUpdateInfo(object);
			}
		}
		return invocation.proceed();
	}

	@Override
	public Object plugin(Object target) {
		return Plugin.wrap(target, this);
	}

	@Override
	public void setProperties(Properties properties) {

	}

	/**
	 * 设置 createTime&createBy
	 * @param object
	 * @throws Throwable
	 */
	private void reflectCreateInfo(Object object) throws Throwable {
		UserInfo userInfo = oAuthUtils.getUserInfo();
		BaseEntity e = (BaseEntity) object;
		if (userInfo != null) {
			e.setCreateBy(userInfo.getUsername());
		}
		e.setCreateTime(new Date());
	}

	/**
	 * 设置 updateTime&updateBy
	 * @param object
	 * @throws Throwable
	 */
	private void reflectUpdateInfo(Object object) throws Throwable {
		if (object instanceof BaseEntity) {
			UserInfo userInfo = oAuthUtils.getUserInfo();
			BaseEntity e = (BaseEntity) object;
			if (userInfo != null) {
				e.setUpdateBy(userInfo.getUsername());
			}
			e.setUpdateTime(new Date());
		}
	}
}

 

你可能感兴趣的:(java)