18

So with JPA/Hibernate you can certainly load an entity "proxy" without hitting the database using something like session.load() or entityManager.getReference().

However, it seems it's impossible to set a property on these "proxies" without Hibernate initializing the proxy from the database. Therefore, you can't persist just the changed values (via @DynamicUpdate on the entity) without a select.

I believe this is just the way it is and if you want update without select you have to roll it yourself. I'd be delighted if somebody could prove me wrong! Am I missing something?

Onur A.
  • 3,007
  • 3
  • 22
  • 37
rogiller
  • 895
  • 1
  • 9
  • 22
  • 1
    In my opinion real question (maybe You think in the same way) isn't "how to update without select" but "how to update in way, that is compatible with JPA philosophy". I want say, few method exists, but breakes cache, session or @PrePersist java code. For better discusion 13.3 from https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/batch.html (see 'disclaimers', that is my way of thinking). Good question, my "Up" – Jacek Cz Aug 20 '17 at 11:17
  • Could you say if you have found a solution? – Pavel_K May 03 '20 at 20:02

2 Answers2

2

I'm afraid you are correct, as written in the java-doc of @DynamicUpdate: "Note, for re-attachment of detached entities this is not possible without select-before-update being enabled."

The answer given by nicolasl is not correct for this case, implementing persistable is required if you wish to control whether persist or merge is triggered when using CrudRepository.save()

Uri Loya
  • 1,181
  • 2
  • 13
  • 34
-1

AFAIK the select is executed by the merge operation with the only purpose of checking if the entity already exists in your DB. If that is correct, you could implement your own verification like they say in their documentation:

Implementing Persistable: If an entity implements Persistable, Spring Data JPA delegates the new detection to the isNew(…) method of the entity. See the JavaDoc for details.

Implementing EntityInformation: You can customize the EntityInformation abstraction used in the SimpleJpaRepository implementation by creating a subclass of JpaRepositoryFactory and overriding the getEntityInformation(…) method accordingly. You then have to register the custom implementation of JpaRepositoryFactory as a Spring bean. Note that this should be rarely necessary. See the JavaDoc for details.

(https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.entity-persistence.saving-entites)

I've never had to implement such thing, but I guess you could give it a try...

Hope this helps you

Cheers

Nikao

nicolasl
  • 421
  • 3
  • 16