Spring Data:带有注释的方法@Query无法按预期工作

时间:2015-09-22 11:32:55

标签: java junit transactions spring-data dao

我尝试用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

此测试方法返回AssertionErrorExpected 0 but was 1.

这意味着makeAllUnactive没有改变Entitites OR的状态,但它们是不可见的。

请您帮我理解我的代码中的“差距”在哪里?

1 个答案:

答案 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