Spring Data JPA – Why are changes to a returned Entity automatically persisted?

That’s a fundamental principle of JPA. You work with attached (managed) entities, and every modification made on these managed entities is automatically made persistent.

If you don’t want your changes to be persistent, then don’t make changes, or rollback the transaction.

Working on detached entities would be a nightmare, because it would prevent lazy-loading all the associations. You can always call EntityManager.detach() on your entities, but I really wouldn’t do that. Just try to understand how it works and deal with it. There are much more benefits than disadvantages. One of them being that you don’t even have to think about saving all the changes that a complex business logic might do, since it’s all done for you by JPA, transparently.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)