MyBatis: Automatically set timestamps for beans saved

The Problem

When a bean is inserted or updated, its "createdAt" or "updatedAt" should be set as the current time. MyBatis won’t do that for you by default.

You can manually set them before inserting them. But you may forget it.

Solution

The solution is to have a MyBatis interceptor which does the job before a bean is saved.

@Intercepts({ @Signature(type = Executor.class, method = "update", args = {
		MappedStatement.class, Object.class }) })
public class RepoInterceptor implements Interceptor {

	@Override
	public Object intercept(Invocation invocation) throws Throwable {
		MappedStatement stmt = (MappedStatement) invocation.getArgs()[0];
		Object param = invocation.getArgs()[1];
		if (stmt == null) {
			return invocation.proceed();
		}

		if (stmt.getSqlCommandType().equals(SqlCommandType.INSERT)) {
			if (param != null && param instanceof EntityBase) {
				EntityBase e = (EntityBase) param;
				if (e.getCreatedAt() == null) {
					e.setCreatedAt(new GregorianCalendar());
				}
			}
		}

		if (stmt.getSqlCommandType().equals(SqlCommandType.UPDATE)) {
			if (param != null && param instanceof EntityBase) {
				EntityBase e = (EntityBase) param;
				if (e.getUpdatedAt() == null) {
					e.setUpdatedAt(new GregorianCalendar());
				}
			}
		}

		return invocation.proceed();
	}

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

	@Override
	public void setProperties(Properties properties) {

	}
}

And in mybatis-config.xml

 


	


Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.