Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/spring-boot/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring Boot中的事务测试-如何获取当前会话?_Spring_Spring Boot_Hibernate - Fatal编程技术网

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异常处理。