首页 > 解决方案 > Spring Boot 中的事务测试 - 如何获取当前会话?

问题描述

Spring 文档对测试中的误报发出警告,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();

如 Spring Boot 文档中所述?

标签: springspring-boothibernate

解决方案


推荐阅读