我使用spring 4.3.1,hibernate 4.3.11。 我有一个hibernate延迟加载的问题。 我有两个例子 第一次正常
@Test
@Transactional
public void lazy1() {
List<WorkActivity> list = workActivityFacade.findAll();
list.stream().forEach(wa -> wa.getWorkActivityTelephonyStatusMappings().size());
}
第二个用org.hibernate.LazyInitializationException失败:无法懒惰地初始化角色集合:WorkActivity.workActivityTelephonyStatusMappings,无法初始化代理 - 没有会话
@Test
public void lazy2() {
test();
}
@Transactional
public void test() {
List<WorkActivity> list = workActivityFacade.findAll();
list.stream().forEach(wa -> wa.getWorkActivityTelephonyStatusMappings().size());
}
我的问题是 - 为什么? 据我所知,如果您在同一个会话中读取并运行延迟加载,或者更常见,在一个持久化上下文中,延迟加载将起作用。 WorkActivityFacade是ejb有状态bean,它使用事务持久化上下文包装实体管理器。为什么在第一种情况下事务上下文是在方法启动时创建的并且在方法运行期间存在,但在第二种情况下它只在bean中创建?
UPD1 - 我的测试类的完整代码
@RunWith(SpringInstanceTestClassRunner.class)
@SpringApplicationConfiguration(Application.class)
public class WorkActivityFacadeTest {
@Autowired
private WorkActivityFacade workActivityFacade;
@Autowired
private TelephonyStatusFacade telephonyStatusFacade;
@Autowired
private WorkActivityTelephonyStatusMappingFacade mappingFacade;
Random r = new Random();
private static TelephonyStatus telephonyStatus;
@Before
public void setUp() {
telephonyStatus = telephonyStatusFacade.create(new TelephonyStatus("test", Color.CYAN, "s" + r.nextDouble()));
}
@After
public void tearDown() {
//telephonyStatusFacade.remove(telephonyStatus);
}
protected WorkActivity initializeEntity() {
WorkActivity wa = new WorkActivity(Color.CYAN, "test activity", true, false, false);
//wa.setTelephonyStatusList(Collections.singletonList(telephonyStatus));
return wa;
}
@Test
public void lazy() {
WorkActivity created = workActivityFacade.create(initializeEntity());
mappingFacade.create(new WorkActivityTelephonyStatusMapping(created, telephonyStatus));
}
@Test
@Transactional
public void lazy1() {
List<WorkActivity> list = workActivityFacade.findAll();
list.stream().forEach(wa -> wa.getWorkActivityTelephonyStatusMappings().size());
}
@Test
public void lazy2() {
test();
}
@Transactional
public void test() {
List<WorkActivity> list = workActivityFacade.findAll();
list.stream().forEach(wa -> wa.getWorkActivityTelephonyStatusMappings().size());
}
}