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

8bitjunkie picture 8bitjunkie · Nov 27, 2012 · Viewed 14.5k times · Source

I present the question with an example.

Assert that we have a Repository such as the below:

public interface ExampleObjectRepository extends CrudRepository<ExampleObject, Long> {

}

By extending the JpaRepository interface, the ExampleObject repository inherits the following method:

T findOne(ID id);

Now, I have observed that, if I receive a reference to an ExampleObject after a call to this method, any manipulations that I make to this method are automatically saved to the database, for example:

ExampleObject pointInCase = exampleObjectRepository.findOne(1L);
pointInCase.setName("Something else");

Reading around the subject, I understand this this signfies that ExampleObject instance is not detached.

This goes against my expectations. I would have expected that I would need to use the save method inherited from CrudRepository in order to save the changes:

T save(T entity);

Would anyone be kind enough to confirm that objects returned from a Spring Data JPA Repository remain attached as standard, and explain how to use the API to mark a method in the repository such that it only returns detached references?

I imagine that changing the entity's state may also change its definition when it is used with said save(T entity) method, so I would also appreciate an understanding of how identity for updates are handled.

Answer

JB Nizet picture JB Nizet · Nov 27, 2012

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.