2

This is a curiosity question based on the fact that in Java everything is passed by value. The signature of the save method is:

<S extends T> S save(S entity);

Say I have this code :

MyEntity entity = new MyEntity();
entity.setId(null);
entity.setName("entity");

MyEntity savedEntity = repository.save(entity);

When calling repository.save(entity), isn't entity updated in the save method? I mean at the end of save execution, savedEntity and entity have the same state, so why returning it ?

Thanks for your clarification.

Oliver Drotbohm
  • 80,157
  • 18
  • 225
  • 211
akuma8
  • 4,160
  • 5
  • 46
  • 82
  • 2
    https://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/repository/CrudRepository.html#save-S- *"Saves a given entity. Use the returned instance for further operations as the save operation might have changed the entity instance completely."* – luk2302 Apr 27 '21 at 15:52
  • @luk2302 I updated my question to be clearer. I already read the doc too. – akuma8 Apr 27 '21 at 16:00
  • That's because during INSERT statement in db values for some columns can be generated. For example uuid or timestamp. – Sergey Vasnev Apr 27 '21 at 16:04
  • @SergeyVasnev I took a look at the `save` implementation, internally it uses `EntityManager#persist(..)` method which returns nothing `public void persist(Object entity)` – akuma8 Apr 27 '21 at 17:00
  • 1
    Its easier to follow code that acts like objects are immutable even when they aren't. – Deadron Apr 27 '21 at 17:06

0 Answers0