0

从我到目前为止所读到的内容中,我了解到使用事务将是解决 hibernate 延迟加载问题的解决方案。该会话将在服务层的整个事务期间可用,无需进一步说明。

所以也许我错误地配置了我的事务管理?在春季和休眠方面,我实际上是一个新手,但也许你们可以帮助我。

我的配置:

<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)如果在该特定方法中实际保存/更新了任何内容,则使用注释。

我是否需要配置其他内容以确保我可以在我的服务中加载正确的关联,或者这通常由事务处理?

现在我对我应该做什么有点困惑,所以请帮助我:)

4

2 回答 2

1

我认为到目前为止我对 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>
于 2010-10-23T09:17:10.453 回答
1

延迟加载问题和事务并没有真正相互关联。但那是另一回事了 :) 除了访问 bean 中的 session 之外,你做得很好。不知道你将如何做到这一点。标准解决方案(在 spring 2.x 中,不确定 3.x,还没有查看)是使用 HibernateDaoSupport 作为类的基类,如果您将访问会话。但就我个人而言,这看起来有点狡猾,因为增加了对 Spring 特定类的依赖。更好的方法是将会话注入到您的 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

于 2010-10-21T23:36:25.817 回答