我尝试用Repository
测试覆盖我的junit
代码,但出乎意料地我遇到了以下问题:
@Test
@Transactional
public void shoudDeactivateAll(){
/*get all Entities from DB*/
List<SomeEntity> someEntities = someEntityRepository.findAll();
/*for each Entity set 1 for field active*/
someEntities.forEach(entity ->
{entity.setActive(1);
/*save changes*/
SomeEntityRepository.save(entity);});
/*call service, which walks through the whole rows and updates "Active" field to 0.*/
unActiveService.makeAllUnactive();
/*get all Entities again
List<SomeEntity> someEntities = SomeEntityRepository.findAll();
/*check that all Entities now have active =0*/
someEntities.forEach(entity -> {AssertEquals(0, entity.getActive());});
}
其中:
makeAllUnactive()
方法只是@Query
:
@Modifying
@Query(value = "update SomeEntity e set v.active=0 where v.active =1")
public void makeAllUnactive();
而且:someEntityRepository
扩展了JpaRepository
此测试方法返回AssertionError
:Expected 0 but was 1.
这意味着makeAllUnactive
没有改变Entitites OR的状态,但它们是不可见的。
请您帮我理解我的代码中的“差距”在哪里?
答案 0 :(得分:1)
:
@Query(value = "update SomeEntity e set v.active=0 where v.active =1")
你应该把它改成:
@Query(value = "update SomeEntity e set e.active=0 where e.active =1")
如果不起作用,请在运行SomeEntityRepository.save(entity);
编辑:
您应在clearAutomatically
中启用@Modifying
标记,以便更新EntityManager
。但请记住,它也可能导致所有未刷新的更改失去。如需更多阅读,请查看:
http://docs.spring.io/spring-data/jpa/docs/1.5.0.M1/reference/htmlsingle/#jpa.modifying-queries