![](/img/trans.png)
[英]Testing lazy loading in hibernate (java spring with transactions)
[英]Spring transactions & hibernate: lazy initialization
從到目前為止的閱讀中,我了解到使用事務將是休眠休眠加載問題的解決方案。 該會話將在服務層的整個事務過程中可用,而沒有其他建議。
因此,也許我沒有正確配置事務管理? 在春季和冬季,我實際上是一個新手,但是也許你們可以幫我一下。
我的配置:
<bean class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"
id="sessionFactory">
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
</bean>
<!-- Hibernate Template bean that will be assigned to DAOs. -->
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
<!--
Transaction manager for a single Hibernate SessionFactory (alternative
to JTA)
-->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref local="sessionFactory" />
</property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
我的DAO實現將只具有@Repository
批注和使用自動裝配注入的Hibernate-template
bean。
服務實現的典型標頭為:
@Service
@Transactional(readOnly=true)
public class LeerlingServiceImpl implements LeerlingService {
@Autowired
LeerlingDAO leerlingDAO;
@Autowired
LeerplanDAO leerplanDAO;
如果在該特定方法中實際保存/更新了任何內容,則使用@Service(readOnly=false)
批注。
我是否需要配置其他內容以確保可以在我的服務中加載正確的關聯,還是通常由事務處理?
現在,我對應該實際執行的操作感到有些困惑,所以請幫助我:)
延遲加載問題和事務之間並沒有真正的關聯。 但這是另一個故事:)除了可以訪問bean中的會話之外,您還做得很好。 不確定您將如何執行此操作。 標准解決方案(在Spring 2.x中,尚不確定3.x,尚未使用)是將HibernateDaoSupport用作要訪問會話的類的基類。 但是就我個人而言,這對我來說似乎有點狡猾,因為增加了對特定於Spring的類的依賴。 更好的方法是將會話注入到bean中。 為此,您需要聲明您的會話bean,其定義類似於該bean:
<bean name="hibernateSession" class="org.springframework.orm.hibernate3.SessionFactoryUtils" factory-method="getSession"
scope="prototype">
<constructor-arg index="0" ref="hibernateSessionFactory"/>
<constructor-arg index="1" value="false"/>
<aop:scoped-proxy/>
</bean>
然后使用它。
這是詳細信息:
http://stas-blogspot.blogspot.com/2009/10/hibernate-spring-in-standalone.html
我認為到目前為止我對Spring的了解還很糟糕。 實際上,我們的會話管理沒有真正的管理。 基本上現在發生的是:您可以從DAO中獲取數據,但是在收到數據之后,由於會話已關閉,您甚至無法加載惰性集合。
現在我們使用休眠攔截器,它在每個請求的開始將會話附加到線程,並在結束時將其關閉。 這並不總是最理想的解決方案,但是對於一個學校項目,我不會太在意。
另一個解決方案似乎是:以@around
的方式添加AOP,以使會話僅在服務方法調用期間可用。 我認為這是最好的解決方案,但是,對於該項目,我現在不會對此進行深入探討。 好消息是我知道它的存在。
這篇文章對我也有很大幫助: http : //www.jroller.com/kbaum/entry/orm_lazy_initialization_with_dao
對於那些感興趣的人:這是我必須添加的內容:在Spring MVC 3.0中,有一個名為mvc:intereceptors
的新功能,使我鍵入的xml更少。
<!-- WEB-INF/applicationContext.xml or your own XML config file -->
<mvc:interceptors>
<bean
class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor">
<property name="sessionFactory">
<ref local="sessionFactory" />
</property>
</bean>
</mvc:interceptors>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.