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?

6
  • 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. Commented May 14, 2018 at 13:14
  • Like clearing the cache or selecting projection instead of the entities. Or simply avoid changes on your "managed" entities Commented May 14, 2018 at 13:15
  • Possible duplicate of Transactional saves without calling update method Commented May 14, 2018 at 13:24
  • I would give a try to @Transactional(readOnly=true). Commented May 14, 2018 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 Commented May 14, 2018 at 13:32

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I'll leave this link here to cover projection query: vladmihalcea.com/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.