Spring documentation
警告
假阳性
在里面
Transactional
测试并提出以下建议:
// ...
@Autowired
SessionFactory sessionFactory;
@Transactional
@Test // no expected exception!
public void falsePositive() {
updateEntityInHibernateSession();
// False positive: an exception will be thrown once the Hibernate
// Session is finally flushed (i.e., in production code)
}
@Transactional
@Test(expected = ...)
public void updateWithSessionFlush() {
updateEntityInHibernateSession();
// Manual flush is required to avoid false positive in test
sessionFactory.getCurrentSession().flush();
}
// ...
我有以下基类:
@SpringBootTest
@Transactional
@AutoConfigureMockMvc
public abstract class BaseSpringBootTest {
一个类,它扩展到我想应用这个方法的地方
sessionFactory
public class EmployeeRepositoryTest extends BaseSpringBootTest {
@Autowired
SessionFactory sessionFactory
但我得到了:
NoSuchBeanDefinitionException: No qualifying bean of type 'org.hibernate.SessionFactory' available
@Autowired
EntityManagerFactory entityManagerFactory;
然后打电话:
SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
sessionFactory.getCurrentSession();
org.hibernate.HibernateException: No CurrentSessionContext configured!
我如何获得参考
currentSession
在一次测试中,我终于可以打电话给:
sessionFactory.getCurrentSession().flush();