【发布时间】:2015-07-15 20:28:20
【问题描述】:
我正面临与此非常相似的问题:Yet another LazyInitializationException even with OpenSessionInViewFilter
我使用 Hibernate 4.2.7.Final。我有一个这样映射的实体:
@Entity
@Table(...)
public class A {
...
@OneToMany(fetch=FetchType.LAZY, mappedBy="b")
private Set<B> bSet;
...
}
它会加载大量数据,这就是为什么我需要在需要时加载它。所以我用这个控制器请求映射加载了一个页面:
@RequestMapping("/getDetails")
public ModelAndView showView(Model model) {
...
for(B b : myService.getBSet()) {...}
...
}
服务正在交易中:
@Service
@Scope(value="session")
@Transactional("ora11transactionManager")
public class MyServiceImpl implements MyService {
private A a;
...
public Set<B> getBSet() {
return a.getBSet();
}
}
hibernate.cgf.xml 中的事务管理器:
<bean id="ora11sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="ora11source"/>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.show_sql">${debug}</prop>
<prop key="hibernate.format_sql">false</prop>
<prop key="hibernate.connection.characterEncoding">UTF-8</prop>
<prop key="hibernate.jdbc.use_get_generated_keys">true</prop>
<prop key="hibernate.cache.use_second_level_cache">true</prop>
</props>
</property>
<property name="packagesToScan">
<list>
<value>mypackage</value>
</list>
</property>
</bean>
<bean id="ora11transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="ora11sessionFactory" />
</bean>
当我想加载 getDetails 视图时,它会抛出引用服务中该行的异常:
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: <my-package>.A.bSet, could not initialize proxy - no Session
这不是我使用的唯一惰性获取集合,但它在其他任何地方都可以使用。延迟加载必须在事务中,并且在事务中(您可以看到我的服务实现)!我什至在web.xml 中添加了org.springframework.orm.hibernate4.support.OpenSessionInViewFilter。
我找不到任何解决方案,请指教!
更新(我的实体的确切用途):
我有一大组 As,每个 A 都有一组 B。有一个视图可以显示所有 As,它们在列表中并显示在数据表中。在每一行的末尾都有一个按钮,用于调用和操作。在此操作中,我保存了选定的 A(在 myService 中有一个用于选定 A 的设置器)。此操作在控制器 1 中。当我想显示 A 的 Bs 时,我设置了哪个被选中并重定向到另一个视图。此视图由另一个控制器管理,这就是我将所选 A 保存到服务(会话或单例范围)的原因。
@Controller
@Scope("session")
public class Controller1 {
...
public void setSelectedA(A selectedA) {
myService.setSelectedA(selectedA);
}
}
即使在这个方法中我也尝试到达B的集合,但是不起作用(整个服务是事务性的,我尝试只对setselectedA()和getBSet()方法设置事务性注释,但没有成功) .
【问题讨论】:
-
在检索对象 A 时初始化集合 b。
-
我试过了,但遇到了同样的异常。
-
把事务注解放在方法上而不是类上
-
也试过了,没有成功。
标签: spring hibernate transactions lazy-loading