Why use returned instance after save() on Spring Data JPA Repository?

前端 未结 2 1403
夕颜
夕颜 2020-12-02 13:14

Here is the code:

@Repository
public interface AccountRepository extends JpaRepository {}

JpaRepository from

相关标签:
2条回答
  • 2020-12-02 13:36

    The save(…) method of the CrudRepository interface is supposed to abstract simply storing an entity no matter what state it is in. Thus it must not expose the actual store specific implementation, even if (as in the JPA) case the store differentiates between new entities to be stored and existing ones to be updated. That's why the method is actually called save(…) not create(…) or update(…). We return a result from that method to actually allow the store implementation to return a completely different instance as JPA potentially does when merge(…) gets invoked.

    So generally it's more of an API decision to be lenient (permissible, tolerant) regarding the actual implementation and thus implementing the method for JPA as we do. There's no additional proxy messaging done to the entities passed.

    0 讨论(0)
  • 2020-12-02 13:38

    You missed the second part: if the entity isn't new, merge is called. merge copies the state of its argument into the attached entity with the same ID, and returns the attached entity. If the entity isn't new, and you don't use the returned entity, you'll make modifications to a detached entity.

    0 讨论(0)
提交回复
热议问题