Search code examples
javahibernatejpapersistence

cannot update without issuing select on using setter after getReference() of hibernate JPA


I have the following method -

 @Transactional
 public void savethis(){
    EntityObject t = entityManagerTreasury.getReference(EntityObject.class, 1);
    t.setAction("abc");
 }

Now, going in line with the following answer - https://stackoverflow.com/a/1608621/4881766

I should be only seeing an update query in my sql logs.

However the behaviour i've observed is as follows -

  1. Given code - select and then update
  2. commenting the t.setAction("abc"); line - No select and no update
  3. replacing getReference() with find() - select and then update

The behaviour i was expecting was that if i use any getter on the proxy, then a select should be issued, but when only using a setter, i wanted the changes to be committed at the end of the method with an update and no select being issued.

Turns out, no matter what i do with the proxy object, getter or setter, it issues a select.

I want to update selected fields of an entity for a given id. If there is any way to update any fields that i want without writing jpql or native query, I'd really appreciate it.

Thanks in advance!


Solution

  • From the EntityManager.getReference() documentation:

    Get an instance, whose state may be lazily fetched.

    Therefore, after entityManagerTreasury.getReference no select is issued.

    Only after t.setAction("abc"), if the entity state is not already fetched, a select is issued to fetch the state.

    The point is: the entity manager cannot save the state of an entity unless the entity state is fetched. Therefore you cannot skip the prior select, unless you use JPQL.