我正在使用弹簧配置的休眠应用程序。有事务管理和一个定义为 entityInterceptor 的 auditInterceptor。当我调试代码时,我正在输入 entityInterceptors 方法并设置日期,但是在保存结束时它们不在数据库中:(。
考虑以下配置
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<value>
hibernate.dialect=${hibernate.dialect}
hibernate.show_sql=${hibernate.show_sql}
hbm2ddl.auto=${hbm2ddl.auto}
</value>
</property>
<property name="schemaUpdate">
<value>true</value>
</property>
<property name="annotatedClasses">
<list>
.. bunch of annotatedClasses" ...
</list>
</property>
</bean>
<bean name="auditInterceptor" class="com.mbalogos.mba.dao.AuditInterceptor" />
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
<property name="entityInterceptor" ref="auditInterceptor"/>
</bean>
<bean id="namedQueryDao" class="com.mbalogos.mba.dao.NamedQueryDaoImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
并跟随 entityInterceptor
public class AuditInterceptor extends EmptyInterceptor{
/**
*
*/
private static final long serialVersionUID = -8374988621501998008L;
@Override
public boolean onSave(Object entity, Serializable id, Object[] state,
String[] propertyNames, Type[] types) {
if(entity instanceof DomainObject){
Timestamp date = new Timestamp(new Date().getTime());
((DomainObject)entity).setCreationDate(date);
((DomainObject)entity).setModificationDate(date);
}
return true;
}
@Override
public boolean onFlushDirty(Object entity, Serializable id,
Object[] currentState, Object[] previousState,
String[] propertyNames, Type[] types) {
if(entity instanceof DomainObject){
DomainObject domainObject = (DomainObject)entity;
Timestamp date = new Timestamp(new Date().getTime());
domainObject.setModificationDate(date);
}
return true;
}
@Override
public void onDelete(Object entity, Serializable id, Object[] state,
String[] propertyNames, Type[] types) {
super.onDelete(entity, id, state, propertyNames, types);
}
@SuppressWarnings("rawtypes")
@Override
public void preFlush(Iterator entities) {
super.preFlush(entities);
}
@SuppressWarnings("rawtypes")
@Override
public void postFlush(Iterator entities) {
super.postFlush(entities);
}
}
在保存方法之后,将 sessionFactory 注入到类中
public <T extends DomainObject> T save(T objectToSave) {
Session currentSession = null;
try {
currentSession = sessionFactory.getCurrentSession();
currentSession.save(objectToSave);
return objectToSave;
} catch (Exception ex) {
logger.error(ex);
}
return null;
}
任何人都知道为什么会发生这种行为。哦,我还尝试将 entityInterceptor 放在 sessionFactory 而不是我第一次尝试的 transactionmanager 中,同样的行为:(