Why doesn't my (spring)HibernateTransactionManager work in wicket?

这一生的挚爱 提交于 2019-12-06 04:16:06

It turns out that the problem was not actually in the configuration information that I posted. Sorry!

My above configuration links to an externalized hibernate.cfg.xml, which declared the following property:

    <!-- Enable Hibernate's automatic session context management -->
    <property name="current_session_context_class">thread</property>

I must've copied this from some sample hibernate config file somewhere. This property caused my SessionFactory to ignore the session context provided by spring, and use a thread-local context in its place. Removing this property fixed the problem (hibernate uses the JTA context by default if none is specified).

This can be made much simpler. Read this section 13.3.3 (Hibernate) Declarative transaction demarcation, especially the last part. This is usually enough configuration if you use @Transactional:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans 
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/tx 
       http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
       http://www.springframework.org/schema/aop 
       http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

  <!-- SessionFactory, DataSource, etc. omitted -->

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

  <tx:annotation-driven/>

  <bean id="myProductService" class="product.SimpleProductService">
    <property name="productDao" ref="myProductDao"/>
  </bean>

</beans>

To answer your comments:

No, if you inject the components via Spring, Spring does the wiring, hibernate doesn't need to know anything about spring, that's the whole point of using spring (to decouple the individual layers). Service and dao is a separation that not everybody uses. The important part is that the public methods backed by the interface are marked as transactional, because all methods marked as transactional will be intercepted by a proxy that does the transaction handling, while others won't.

You may want to read the general section about Declarative Transaction Managmenet in Spring to understand the process (this applies to all transactional technologies, not just to hibernate).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!