Spring Boot中的事务测试-如何获取当前会话?
警告Spring Boot中的事务测试-如何获取当前会话?,spring,spring-boot,hibernate,Spring,Spring Boot,Hibernate,警告事务性测试中的误报,并提出以下建议: /。。。 @自动连线 会话工厂会话工厂; @交易的 @测试//没有预期的异常! 公开无效假阳性(){ UpdateEntityHibernateSession(); //假阳性:休眠后将引发异常 //最终刷新会话(即,在生产代码中) } @交易的 @测试(预期=…) public void updateWithSessionFlush(){ UpdateEntityHibernateSession(); //需要手动冲洗,以避免试验中出现假阳性 sess
事务性测试中的误报,并提出以下建议:
/。。。
@自动连线
会话工厂会话工厂;
@交易的
@测试//没有预期的异常!
公开无效假阳性(){
UpdateEntityHibernateSession();
//假阳性:休眠后将引发异常
//最终刷新会话(即,在生产代码中)
}
@交易的
@测试(预期=…)
public void updateWithSessionFlush(){
UpdateEntityHibernateSession();
//需要手动冲洗,以避免试验中出现假阳性
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();
如Spring引导文档中所述?这不是Spring引导文档,而是Spring文档。这是另一回事!。只需插入EntityManager
,因为Spring Boot默认使用JPA。@M.Deinum谢谢,修复了这个问题。我想我只是累了。注入EntityManager
的问题在于,引发的异常不是DataIntegrityViolationException
,而是PersistenceException
。我想这没关系,这是我能找到的最接近真实行为的方法。DataIntegrityViolationException
与Session
之间也不会出现DataIntegrityViolationException,因为直接使用持久性实现可以绕过数据访问技术的Spring异常处理。