0

I have created 2 entities. Now when I retrieve my entities in my backend I verify some things, but when my backend return those entities to my frontend the hibernate try to update automatically the db.

I don't actually run any update in my backend code (I think it`s because I change some data in my entity while i do my logic and remove some properties that I should return to my frontend).

How can I tell to hibernate to not update anything until I run .save or .update explicitly?

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
Fabio Ebner
  • 2,613
  • 16
  • 50
  • 77
  • 1
    That is one of the main feature of hibernate or any other orm, read about hibernate cache or persistence context. Short answer: any change you make in the entities that you retrieve from Db get reflected to the Db at the end of the transaction. Yes there are various way to avoid it. – Zeromus May 14 '18 at 13:14
  • Like clearing the cache or selecting projection instead of the entities. Or simply avoid changes on your "managed" entities – Zeromus May 14 '18 at 13:15
  • Possible duplicate of [Transactional saves without calling update method](https://stackoverflow.com/questions/8190926/transactional-saves-without-calling-update-method) – Aritz May 14 '18 at 13:24
  • I would give a try to `@Transactional(readOnly=true)`. – Aritz May 14 '18 at 13:24
  • @Zeromus it's possible to when I return anything from my db automatic turns detached? the @Transactional(readOnly=true) don't works – Fabio Ebner May 14 '18 at 13:32
  • not that i know of if you stick to entities. your best bet is clearing the cache before ending the transaction, as it just evict all the entities and discard the changes – Zeromus May 14 '18 at 13:33

1 Answers1

3

You already got the pieces in the comments, but let me put it together in an answer:

I think it`s because I change some data in my entity while i do my logic

That interpretation is correct.

If you load an entity via JPA it is attached to a session and every change to it gets tracked and written to the database once you close the session/ commit the transaction.

In order to avoid that you need to remove the entity from the session. You can do that by either

Note that in both cases lazy loading won't work anymore so you'll have to make sure you loaded everything you needed before detaching the entity.

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
  • 1
    I'll leave this link here to cover projection query: https://vladmihalcea.com/the-best-way-to-map-a-projection-query-to-a-dto-with-jpa-and-hibernate/ – Zeromus May 14 '18 at 14:02