junit4 hibernate4 解决 LazyInitializationException 问题

在编写junit4 测试类时 fetch=FetchType.LAZY 延时加载会报错:
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: ins.xxx.xxx.xx, could not initialize proxy - no Session
at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:566)
at

解决方案:
在使用 @Before @After控制session



@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/spring/*.xml"})
public class BaseTestTrueRollback {

@Autowired
private SessionFactory sessionFactory;
private Session session;

@Before
public void openSession() throws Exception {
session = sessionFactory.openSession();// SessionFactoryUtils. getSession(sessionFactory,true);
session.setFlushMode(FlushMode.MANUAL);
TransactionSynchronizationManager.bindResource(sessionFactory,new SessionHolder(session));
}

@After
public void closeSession() throws Exception {
TransactionSynchronizationManager.unbindResource(sessionFactory);
SessionFactoryUtils.closeSession(session);
}

你可能感兴趣的:(junit4 hibernate4 解决 LazyInitializationException 问题)