1.如果使用HibernateTemplate,默认Session在使用后会关闭,如果使用load延迟加载获得Proxy对象后,就无法在前台获取数据。
2.OpenSessionInViewFilter的作用是延长Hibernate中Session的生命周期到页面,使用Proxy时获取数据。
3.使用OpenSessionInViewFilter只需在web.xml中作为一个Filter进行配置,OpenSessionInViewFilter的位置必须在Struts2过滤器前,否则无用
4.使用OpenSessionInViewFilter后,Session的flush mode默认设为manual,此时持久化对象可能会抛异常,因为HibernateTemplate会检查flush mode
protected void checkWriteOperationAllowed(Session session) throws InvalidDataAccessApiUsageException {
if (isCheckWriteOperations() && getFlushMode() != FLUSH_EAGER &&
session.getFlushMode().lessThan(FlushMode.COMMIT)) {
throw new InvalidDataAccessApiUsageException(
"Write operations are not allowed in read-only mode (FlushMode.MANUAL): "+
"Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition.");
}
}
如果小于COMMIT级别,就会抛异常
5.解决的方法是自定义一个继承OpenSessionInViewFitler的类,如用名为OpenSessionInViewFilter,重写getFlushMode方法,返回AUTO或者COMMIT
@Override
protected FlushMode getFlushMode() {
return FlushMode.AUTO;
}
6.此操作并不能保证Session的dml操作成功,因为HibernateTemplate的并不主动提交事务commit,只有FlushMode变化(不是Hibernate中的FlushMode)或者无Transaction时才会flush
protected void flushIfNecessary(Session session, boolean existingTransaction) throws HibernateException {
if (getFlushMode() == FLUSH_EAGER || (!existingTransaction && getFlushMode() != FLUSH_NEVER)) {
logger.debug("Eagerly flushing Hibernate session");
session.flush();
}
}
而一般情况会靠Transaction去处理flush
7.对于6的解决方法,就是让Transaction存在,比如配置TransactionManager