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

后端 未结 3 1078
时光取名叫无心
时光取名叫无心 2020-12-23 17:00

I present the question with an example.

Assert that we have a Repository such as the below:

public interface ExampleObjectRepository extends CrudRepo         


        
3条回答
  •  独厮守ぢ
    2020-12-23 17:31

    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).

提交回复
热议问题