public Object intercept(Invocation invocation) throws Throwable {
return invocation.proceed();
}
@Override
public Object plugin(Object target) {
if (target instanceof DefaultParameterHandler) {
DefaultParameterHandler paramHandler = (DefaultParameterHandler) target;
Object obj = paramHandler.getParameterObject();
if (obj != null) {
if (obj instanceof Auditable) {
DateTime currentTimeStamp = new DateTime();
String currentUser = auditorAwareBean.getCurrentAuditor();
Auditable auditable = (Auditable) obj;
if (auditable.getCreatedDate() == null) {
auditable.setCreatedDate(currentTimeStamp);
auditable.setCreatedBy(currentUser);
}
auditable.setLastModifiedBy(currentUser);
auditable.setLastModifiedDate(currentTimeStamp);
}
}
}
return target;
}
@Override
public void setProperties(Properties properties) {
}
}
In Listing 21-15, the MyBatis @Intercepts annotation is used to indicate to MyBatis that this class
will intercept MyBatis operations. The nested @Signature annotation defines the class, method, and
argument that we want to intercept. In our case, it's the update operation.
Within the class, the MyBatis Interceptor interface is implemented. The main logic for updating the
audit properties of the domain object is in the plugin() method. In the method, we check whether the
target object is of type DefaultParameterHandler, which MyBatis uses for mapping the domain object
properties into the SQL statements. If that's the case, we will check whether the domain object contains
auditable properties by checking whether the class is assignable to the Spring Data Commons Auditable
interface, since all domain objects with those auditing properties implement that interface.
If all the conditions match, then the audit fields will be updated accordingly before MyBatis
performs the mapping operation. As you saw, the MyBatis plug-in system is the trick for intercepting
various mapping operations for custom logic.
For configuration of the plug-in, please refer to the sqlSessionFactory bean definition in the file
mybatis-tx-config.xml.
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home