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.


You can make your Repository return detached entities if your Transaction is scoped to the repository. I.e. your transaction starts with entrance into the repository and gets closed when you code exits the repository.

If you work like this you have to take care that all necessary data gets loaded in one go, because otherwise you will get lazy initialization exceptions. But in many circumstances I consider this desirable because it gives you some control back when and what data is loaded, that otherwise slips easily through your fingers when using JPA.

For modifications I use a different Transaction scope which wraps the complete process of loading, changing (and implicitly persisting).


I also faced the same problem.
But for me, the issue came on custom repository implementation then i added @Transactional(readOnly = true).