简体   繁体   English

Spring数据:带有批注@Query的方法无法正常工作

[英]Spring Data: Method with annotation @Query doesn't work as expected

I try to cover my Repository code with junit tests but unexpectedly I am facing the following problem: 我尝试用junit测试覆盖我的Repository代码,但是出乎意料的是,我面临以下问题:

  @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());});
    } 

where: makeAllUnactive() method is just a @Query : 其中: makeAllUnactive()方法只是一个@Query

 @Modifying
            @Query(value = "update SomeEntity e set v.active=0 where v.active =1")
            public void makeAllUnactive();

And: someEntityRepository extends JpaRepository 并且: someEntityRepository扩展了JpaRepository

This test method return AssertionError : Expected 0 but was 1. 此测试方法返回AssertionErrorExpected 0 but was 1.

it means that makeAllUnactive didn't change the status for Entitites OR did chanches, but they are invisible. 这意味着makeAllUnactive不会更改makeAllUnactive的状态,也不会更改chanch,但是它们是不可见的。

Could you please help me understand where is "gap" in my code? 您能否帮助我了解代码中的“差距”在哪里?

in the query you have: 在查询中,您具有:

@Query(value = "update SomeEntity e set v.active=0 where v.active =1")

you should rather have changed it into: 您应该将其更改为:

@Query(value = "update SomeEntity e set e.active=0 where e.active =1")

if that does not work, try flushing after running SomeEntityRepository.save(entity); 如果不起作用,请在运行SomeEntityRepository.save(entity);之后尝试刷新SomeEntityRepository.save(entity);

EDIT: 编辑:

You should enable clearAutomatically flag in the @Modifying , so that EntityManager will get updated. 您应该在@Modifying启用clearAutomatically标志,以便EntityManager @Modifying更新。 However keep it mind that it may also cause loosing all the non-flushed changes. 但是请记住,它也可能导致丢失所有未刷新的更改。 For some more reading take a look: 有关更多阅读,请查看:

http://docs.spring.io/spring-data/jpa/docs/1.5.0.M1/reference/htmlsingle/#jpa.modifying-queries http://docs.spring.io/spring-data/jpa/docs/1.5.0.M1/reference/htmlsingle/#jpa.modifying-queries

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM