使用 spring jpa 和 spring 测试时数据未插入数据库

data is not insert into db when using spring jpa and spring test

@RunWith(SpringJUnit4ClassRunner.class)
@Transactional
@ContextConfiguration(classes = SimpleConfiguration.class)
public class CustomerSyncRepositoryTest {

    @Autowired
    CustomerSyncRepository customerSyncRepository;


    @Autowired
    CustomerRepository customerRepository;

    @Autowired
    MemberShipRepository memberShipRepository;

    @Test
    public void collectDataTest() {
        CustomerSync customerSyncOne = new CustomerSync();
        customerSyncOne.setMembershipNumber("1");
        customerSyncRepository.save(customerSyncOne);

        Membership membership = new Membership();
        membership.setName("钻石");
        membership = memberShipRepository.save(membership);

        Customer customerOne = new Customer();
        customerOne.setMembershipNumber("1");
        customerOne.setMembership(membership);
        customerRepository.save(customerOne);

        Customer customerTwo = new Customer();
        customerTwo.setMembershipNumber("2");
        customerTwo.setMembership(membership);
        customerRepository.save(customerTwo);

        customerSyncRepository.collectMissingSyncData();
        assertEquals(2, customerSyncRepository.findAll().size());
    }
}

db中应该有2条记录,但是新记录似乎从来没有插入到db中。当我通过启动应用程序对其进行测试时,db 中有 2 条记录。我在单元测试中是否遗漏了任何配置?这是 customerSyncRepository.collectMissingSyncData() 所做的。

public interface CustomerSyncRepository  extends JpaRepository<CustomerSync, String> {
    @Modifying
    @Query(nativeQuery = true, value = "insert into customer_sync(membershipNumber,membership, cnName, enName, phoneNum, password, email, firstname, lastname, active, otherType, otherNum ) SELECT " +
            "a.membershipNumber, " +
            "b.name, " +
            "a.cnName, " +
            "a.enName, " +
            "a.phoneNum ," +
            "a.password, " +
            "a.email, " +
            "a.firstname, " +
            "a.lastname, " +
            "a.active, " +
            "a.otherType, " +
            "a.otherNum " +
            "FROM " +
            "customer a " +
            "JOIN membership b ON (a.membership_id = b.id) " +
            "WHERE " +
            "a.membershipNumber NOT IN (select membershipNumber from customer_sync) ")
    void collectMissingSyncData();

    List<CustomerSync> findBySync(boolean isSync);
}

问题是您保存的实体存储在一级缓存中。换句话说,它们还不在数据库中。

为了解决这个问题,只需将一级缓存的状态刷新到数据库中。

一种方法是像这样将 EntityManager 注入测试 class...

@PersistenceContext
EntityManager entityManager;

... 然后在每次调用 customerRepository.save(..) 之后调用 entityManager.flush()(或者至少在调用 customerSyncRepository.findAll() 之前调用一次)。

另一种选择是简单地调用存储库本身的 flush() 方法——例如,如果您正在使用 Spring Data JPA 存储库。