可以在 EntittManager 和 Repository 之间共享事务

Can share a transaction between EntittManager and a Repository

有没有办法在同一个@Transactional 方法中同时使用 EntityManager 和一些存储库?

在下面的代码中,我希望最后一次评估成功。

@DataJpaTest
public class JobCategoryRepositoryTest {

    [...]

    @Test
    void save_and_check() {
        repository.save(JobCategory.builder("a1").build());
        repository.save(JobCategory.builder("a2").build());
        repository.save(JobCategory.builder("a3").build());
        repository.flush();

        assertThat(repository.getCount()).isEqualTo(3); // OK

        EntityManager em = entityManagerFactory.createEntityManager();
        List<JobCategory> results = em.createQuery("select j from JobCategory j", JobCategory.class).getResultList();
        assertThat(results.size()).isEqualTo(3); // NOT OK
    }

您应该在测试中应用 TestEntityManager。它是一个包装器,创建(或 returns 现有的)EntityManager 保证绑定到当前 运行 Spring 事务。

@DataJpaTest
public class JobCategoryRepositoryTest {

    @Autowired
    private TestEntityManager tem;

    @Test
    void save_and_check() {
        repository.save(JobCategory.builder("a1").build());
        repository.save(JobCategory.builder("a2").build());
        repository.save(JobCategory.builder("a3").build());
        repository.flush();

        assertThat(repository.getCount()).isEqualTo(3); // OK

        EntityManager em = tem.getEntityManager();
        List<JobCategory> results = em.createQuery("select j from JobCategory j", JobCategory.class).getResultList();
        assertThat(results.size()).isEqualTo(3); // OK
    }