Andr1i
Andr1i

Reputation: 329

How to test method from repository which marked as @Modifying?

For example I have

public interface CrudUserRepository extends JpaRepository<User, Integer> {

@Modifying
@Query(nativeQuery = true, value = "UPDATE users SET active=?2 WHERE id=?1")
void setActive(long id, boolean active);
}

In my test I invoking this method and then find by id.

@Autowired
CrudUserRepository crudUser;
@Transactional
@Test
public void setActiveTest(){
    User user = getUser();
    crudUser.save(user);

    crudUser.setActive(user.getId(), true);
    Optional<User> optUser = crudUser.findById(user.getId());
    assert optUser.get().isActive(); //here my test falls

And when I perform crudUser.findById(user.getId()) my optUser contains that user doesn't active but actually he's active (I've tested that by setting @Rollback(false) and manually check in db).

How I can test that case?

Upvotes: 2

Views: 1589

Answers (1)

RJ.Hwang
RJ.Hwang

Reputation: 1913

Because crudUser.save will cache the entity. And when you call crudUser.findById, JPA just get the entity from the cache not from database. crudUser.setActive not update the entity.active in the cache. Change the code like bellow can fix it (clear the JPA cache) :

....
@PersistenceContext
EntityManager entityManager;
...
@Test
public void setActiveTest(){
  ...

  // clear the cache and force crudUser.findById from database
  entityManager.clear();

  Optional<User> optUser = crudUser.findById(user.getId());
  ...
}

Upvotes: 7

Related Questions