Hibernate 延迟加载不会';t与@Postconstruct一起工作
案例:我在@PostConstruct中加载用户对象,当尝试在任何测试方法中获取角色时,我得到lazyinitialization异常,但是当加载任何测试方法中的用户对象,然后获取角色时,一切正常 要求:我希望能够使惰性初始化在测试方法中工作良好,而无需在每个测试方法中加载对象,也无需在init方法中加载集合,在单元测试中有没有解决此类问题的好办法Hibernate 延迟加载不会';t与@Postconstruct一起工作,hibernate,spring,unit-testing,lazy-loading,lazy-initialization,Hibernate,Spring,Unit Testing,Lazy Loading,Lazy Initialization,案例:我在@PostConstruct中加载用户对象,当尝试在任何测试方法中获取角色时,我得到lazyinitialization异常,但是当加载任何测试方法中的用户对象,然后获取角色时,一切正常 要求:我希望能够使惰性初始化在测试方法中工作良好,而无需在每个测试方法中加载对象,也无需在init方法中加载集合,在单元测试中有没有解决此类问题的好办法 @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locati
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
"classpath:/META-INF/spring/applicationContext.xml",
"classpath:/META-INF/spring/applicationSecurity.xml" })
@TransactionConfiguration(defaultRollback = true)
@Transactional
public class DepartmentTest extends
AbstractTransactionalJUnit4SpringContextTests {
@Autowired
private EmployeeService employeeService;
private Employee testAdmin;
private long testAdminId;
@PostConstruct
private void init() throws Exception {
testAdminId = 1;
testAdmin = employeeService.getEmployeeById(testAdminId);
}
@Test
public void testLazyInitialization() throws Exception {
testAdmin = employeeService.getEmployeeById(testAdminId);
//if i commented the above assignment, i will get lazyinitialiaztion exception on the following line.
Assert.assertTrue(testAdmin.getRoles().size() > 0);
}
}
使用
@Before
而不是@PostConstruct
:
@org.junit.Before
public void init() throws Exception {
testAdminId = 1;
testAdmin = employeeService.getEmployeeById(testAdminId);
}
与
@PostConstruct
(即使显式标记为@Transactional
)也不会在事务中运行)相反,@Before
和@Before
方法始终参与测试(仅回滚)事务。它没有帮助。JUnit框架无论如何都会为每个测试方法构造一个新对象,因此即使您确实得到了@PostConstruct
来执行您想要的操作,它也不会为所有方法初始化一次。唯一的all方法初始化是JUnits@BeforeClass
,这可能仍然不是您想要的,因为它是静态的,并且在spring初始化之前运行。您可以尝试其他框架…它工作得很好,但是init方法需要公开,感谢您的快速回复。