开发者

Spring + Hibernate session management

开发者 https://www.devze.com 2023-03-14 05:21 出处:网络
I have been reading about using Spring with Hibernate and I am really confused about session management. Hopefully someone can clear a few things up for me,

I have been reading about using Spring with Hibernate and I am really confused about session management. Hopefully someone can clear a few things up for me,

First of all I have no idea how sessions are managed when using HibernateTemplate. Is a session opened and closed when you call a method Eg Save() on the template? When you use the find() method, are detached objects returned?

I have read the Spring section on transacti开发者_如何学Pythonons but it mostly talks about handling exceptions. I was hoping to find some way of binding a hibernate session to a Spring transaction so that I can commit changes to hibernate objects when the transaction finishes. Is there a way to achieve this?


Spring manages the session for you. Looking in the documentation, specifically in section 13.3.1, you see

<bean id="mySessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="dataSource" ref="myDataSource"/>
    <property name="mappingResources">
      <list>
        <value>product.hbm.xml</value>
      </list>
    </property>
    <property name="hibernateProperties">
      <value>
        hibernate.dialect=org.hibernate.dialect.HSQLDialect
      </value>
    </property>
  </bean>

and then in section 13.3.3 you see this

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

If you look carefully, you will see that the session factory uses the datasource, and the transaction manager uses the sessionfactory, that way Spring could get your sessions for you, and wrap all your persistence code in a transaction.

0

精彩评论

暂无评论...
验证码 换一张
取 消