写单测,为了让单测自动回滚,在单测方法上增加了@Transactional。单测逻辑如1)创建实体,2)更新实体属性,3)读取实体。
发现在更新实体后的属性并未更新,猜测原因应该是事务提交之前,数据未到数据库,各条语句的执行结果有对应的缓存,需要刷新才能保持一致性?
代码如:
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestRepositoryTest {
@Autowired
private LisenceRepository lisenceRepository;
@PersistenceContext
private EntityManager entityManager;
@Test
@Transactional
public void testB() throws Exception {
//1)创建实体
Lisence lisence = new Lisence();
lisence.setIsValid(true);
lisence.setLisenceContent("test");
lisence.setCreatedDate(new Date());
lisenceRepository.save(lisence);
//2)更新实体
List<Lisence> lisences = lisenceRepository.findByLisenceContent("test");
Assert.assertNotNull(lisences);
Assert.assertTrue("Should have valid lisence", lisences.size() > 0);
lisenceRepository.updateIsValidById(lisences.get(0).getId(), false);
// entityManager.flush();
// entityManager.clear();
//3)验证更新过的实体属性
Optional<Lisence> invalidLisence = lisenceRepository.findById(lisences.get(0).getId());
Assert.assertTrue(invalidLisence.isPresent());
Assert.assertFalse("Lisence should be invalid", invalidLisence.get().getIsValid());
}
}
两种方式可以解决:
1)引入EntityManager,在更新语句实行完成之后,调用flush()和clear(),
2)jpa的更新语句增加 flushAutomatically=true, clearAutomatically=true:
@Transactional
public interface LisenceRepository extends JpaRepository<Lisence, Long> {
@Modifying(flushAutomatically=true, clearAutomatically=true)
@Query(value = "update Lisence set is_valid = :is_valid where id = :id", nativeQuery = true)
void updateIsValidById(@Param("id") Long id, @Param("is_valid") boolean isValid);
}
参考:
https://blog.csdn.net/cyoubunketu/article/details/79740562
https://stackoverflow.com/questions/33074547/spring-boot-configure-entitymanager