【问题标题】:How can I globally set FlushMode for Hibernate 4.3.5.Final with Spring 4.0.6?如何使用 Spring 4.0.6 为 Hibernate 4.3.5.Final 全局设置 FlushMode?
【发布时间】:2014-10-26 12:52:33
【问题描述】:

我正在尝试使用 Hibernate 4.3.5.Final 和 Spring 4.0.6 升级我们的应用程序。在我的应用程序中进行数据库写入操作的任何地方都会出现如下错误:

Caused by: org.springframework.dao.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.
  at org.springframework.orm.hibernate4.HibernateTemplate.checkWriteOperationAllowed(HibernateTemplate.java:1135)
  at org.springframework.orm.hibernate4.HibernateTemplate$26.doInHibernate(HibernateTemplate.java:826)
  at org.springframework.orm.hibernate4.HibernateTemplate.doExecute(HibernateTemplate.java:340)
  at org.springframework.orm.hibernate4.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:308)
  at org.springframework.orm.hibernate4.HibernateTemplate.deleteAll(HibernateTemplate.java:823)
  ... 

以下是我对 sessionFactory 和 transactionManager 的 spring 配置:

<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
  <property name="dataSource" ref="dataSource"/>
  <property name="mappingResources">
    <list>
      <value>com/mycompany/Person.hbm.xml</value>   
    </list>
  </property>
  <property name="hibernateProperties">
    <props>
      <prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>
    </props>
  </property>
</bean>

<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
  <property name="sessionFactory" ref="sessionFactory"/>
</bean>

1:

为了全局设置flushMode以使应用程序以与以前相同的方式工作,我需要将flushMode全局设置为AUTO,因此我不想使用@Transactional(readOnly = false)方法。

2:

在下面的帖子中,有人建议将 singleSession 设置为 false, Java / Hibernate - Write operations are not allowed in read-only mode

Spring 文档建议指定 "singleSession"="false" 有副作用: http://docs.spring.io/spring/docs/4.0.6.RELEASE/javadoc-api/org/springframework/orm/hibernate3/support/OpenSessionInViewInterceptor.html

3:

我在 web.xml 中看到了很多类似下面的建议,它允许你拦截 hibernate3 会话并提供一个版本的会话,例如冲洗模式。自动。但是,当您使用 org.springframework.orm.hibernate4.support.OpenSessionInViewFilter 时,这在 hibernate 4 中不起作用。

<filter>
    <filter-name>openSessionInViewFilter</filter-name>
    <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
    <init-param>
        <param-name>flushMode</param-name>
        <param-value>AUTO</param-value>
    </init-param>
</filter>

4:

下面建议的方法是使用 JPA 事务管理器,它遵循 HibernateJpaDialect 的复杂重新实现。我目前没有使用 JPA,而且这种方法似乎不够简单。 How do I set flush mode to "COMMIT" in my configuration files?

5:

我尝试在我的 spring 配置中包含以下内容(遵循Spring ORM 4.0.5 and Hibernate 4.3.5 - Cant save to database 的建议), 它似乎不起作用,人们建议使用 web.xml 方法: Spring and Hibernate suddenly set the transaction to readonly

<tx:advice id="transactionAdvice" transaction-manager="transactionManager" >
  <tx:attributes>
    <tx:method name="*" read-only="false"/>
  </tx:attributes>
</tx:advice>

问题:

谁能建议一种简单的方法来允许为 Hibernate 4.3.5.Final 和 Spring 4.0.6 设置 FlushMode?​​p>

【问题讨论】:

  • 如果未设置刷新模式,我怀疑有错误或缺少事务管理。您拥有HibernateTransactionManager 的事实并不意味着您已正确设置了 tx。此外,仅添加 &lt;tx:advice /&gt; 而不添加 &lt;aop:config /&gt; 来应用它几乎是没有用的。
  • @M.Deinum 感谢您的评论。就我而言,我需要在应用程序中镜像以前的行为,即使用 FlashMode.AUTO(它是旧 Hibernate 版本 3.0.5 的默认设置)。您的回答使我能够对更清洁的解决方案进行进一步调查(如果全局设置只读为 false 满足我们应用程序的需要)。

标签: java spring hibernate hibernate-4.x spring-4


【解决方案1】:

我最终用自定义实现覆盖了 OpenSessionInViewFilter:

1:

web.xml:

<filter>
  <filter-name>openSessionInViewFilter</filter-name>
  <filter-class>com.mycompany.AutoFlushOpenSessionInViewFilter</filter-class>
</filter>

<filter-mapping>
  <filter-name>openSessionInViewFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

<listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
  • Spring 需要 ContextLoaderListener 才能工作。
  • AutoFlushOpenSessionInViewFilter 用于拦截来自 /* url 模式的请求

2:

AutoFlushOpenSessionInViewFilter:

import org.hibernate.FlushMode;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.orm.hibernate4.support.OpenSessionInViewFilter;

public class AutoFlushOpenSessionInViewFilter extends OpenSessionInViewFilter {

  protected Session openSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {
    try {
      Session session = sessionFactory.openSession();
      session.setFlushMode(FlushMode.AUTO); // This line changes the default behavior
      return session;
    } catch (HibernateException ex) {
      throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
    }
  }
}
  • OpenSessionInViewFilter 是拦截休眠会话的默认方式 (http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/orm/hibernate4/support/OpenSessionInViewFilter.html)
  • openSession 方法打开一个休眠会话。 Hibernate 会使用这个会话而不是创建一个新的会话
  • hibernate3.support.OpenSessionInViewFilter 允许你提供一个 FlushMode,hibernate4.support.OpenSessionInViewFilter 硬编码这个值,所以我用我自己的实现覆盖它
  • 确保您的 sessionFactory bean 名称是 sessionFactory。否则,您需要在 web.xml 中将 sessionFactoryBeanName 设置为过滤器 init-param

3:

所有 Spring bean 都需要在 Web 应用程序上下文 (web.xml) 中注册:

<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>
    classpath:appContext.xml
    ...
  </param-value>
</context-param>

4:

确保仅在需要使用时从应用程序上下文中获取 Spring bean。下面是一个例子: http://sujitpal.blogspot.co.uk/2007/03/accessing-spring-beans-from-legacy-code.html

确保只创建了一份 Spring bean 的副本! 如果使用 org.springframework.context.support.ClassPathXmlApplicationContext 加载 Spring bean,这些 bean 将不会被过滤器拾取。

5:

就我而言,还需要一个 contextId

<context-param>
  <param-name>contextId</param-name>
  <param-value>myApp</param-value>
  <description>Required contextId when filter is supplied</description>
</context-param>

否则我会遇到以下问题:

2014-09-02 10:59:50 StandardContext[/myApp]Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;
  at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:384)
  at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
  at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
  at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3827)
  at org.apache.catalina.core.StandardContext.start(StandardContext.java:4343)
  at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:823)
  at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:807)
  at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:595)
  at org.apache.catalina.core.StandardHostDeployer.addChild(StandardHostDeployer.java:903)
  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  at java.lang.reflect.Method.invoke(Method.java:606)
  at org.apache.commons.beanutils.MethodUtils.invokeMethod(MethodUtils.java:216)
  at org.apache.commons.digester.SetNextRule.end(SetNextRule.java:256)
  at org.apache.commons.digester.Rule.end(Rule.java:276)
  at org.apache.commons.digester.Digester.endElement(Digester.java:1058)
  at org.apache.catalina.util.CatalinaDigester.endElement(CatalinaDigester.java:76)
  at org.apache.xerces.parsers.AbstractSAXParser.endElement(Unknown Source)
  ...

如果有人感兴趣,以下是我的 Ivy.xml 中的内容

<!--Spring 4.0.6.RELEASE -->
<dependency org="org.springframework" name="spring-aop" rev="4.0.6.RELEASE" conf="compile->master,sources,javadoc"/>
<dependency org="org.springframework" name="spring-beans" rev="4.0.6.RELEASE" conf="compile->master,sources,javadoc"/>
<dependency org="org.springframework" name="spring-core" rev="4.0.6.RELEASE" conf="compile->master,sources,javadoc"/>
<dependency org="org.springframework" name="spring-expression" rev="4.0.6.RELEASE" conf="compile->master,sources,javadoc"/>
<dependency org="org.springframework" name="spring-context" rev="4.0.6.RELEASE" conf="compile->master,sources,javadoc"/>
<dependency org="org.springframework" name="spring-jdbc" rev="4.0.6.RELEASE" conf="compile->master,sources,javadoc"/>
<dependency org="org.springframework" name="spring-orm" rev="4.0.6.RELEASE" conf="compile->master,sources,javadoc"/>
<dependency org="org.springframework" name="spring-tx" rev="4.0.6.RELEASE" conf="compile->master,sources,javadoc"/>
<dependency org="org.springframework" name="spring-web" rev="4.0.6.RELEASE" conf="compile->master,sources,javadoc"/>
<dependency org="aopalliance" name="aopalliance" rev="1.0" conf="compile->master,sources,javadoc"/>

<!--Hibernate 4.3.5-->
<dependency org="org.hibernate" name="hibernate-core" rev="4.3.5.Final" conf="compile->master,compile,sources"/>
<dependency org="net.sf.ehcache" name="ehcache-core" rev="2.4.8" conf="compile->master,sources,javadoc"/>
<dependency org="org.slf4j" name="slf4j-api" rev="1.7.5" conf="compile->master,sources,javadoc"/>

希望这对在升级 Spring 和 Hibernate 时遇到相同问题的任何人有所帮助。

【讨论】:

  • OpenSessionInViewFilter 中的刷新模式从不(或手动)是有原因的:)。通常,当您进行适当的 tx 管理时,事务管理器会将其临时设置为 AUTO 直到事务结束。因此,我的建议是,这或多或少表明您在您的应用程序中存在错误或缺少 tx 管理。
  • 嗨@M.Deinum,感谢您的回答。这是否意味着现在 Spring 和 Hibernate 默认执行只读模式(因为默认情况下每个写访问都会获得异常)?如果是这种情况,禁用它并不觉得我们应该使用事务管理,对吧?我不想总是启用事务功能并将 @Transactional(readOnly=false) 添加到每个更新和删除中。如果您或任何人都可以向我指出有关我们应该如何正确实现 hibernate 4 的写访问权限的官方文档,我们将不胜感激!如果事务性是要走的路,那很好。
猜你喜欢
  • 1970-01-01
  • 2016-06-05
  • 2014-10-11
  • 2014-08-16
  • 2014-02-19
  • 1970-01-01
  • 2014-05-24
  • 2014-08-14
  • 2020-07-29
相关资源
最近更新 更多