spring-data JpaRepository save() method side effect

Sergii Bishyr :

I've noticed a very strange behavior with the save(T entity) in the spring-data JpaRepository.

I have the entity Foo foo and I'm trying to save it with repository fooRepository.save(foo). My issue is, the after saving, the instance of foo that I'm passing to the save() method is changed. I do not expect this, and I'm very strange that I can't find any issue related to it.

Is this the expected behavior?

Tim Biegeleisen :

We can try to understand your observations by first checking the Javadoc for CrudRepository:

Saves a given entity. Use the returned instance for further operations as the save operation might have changed the entity instance completely.

One possible explanation here is that when you saved, some other thread or process had also modified the underlying entity. Here is what the save() method actually does:

@Transactional
@Override
public <S extends T> S save(S entity) {

    if (entityInformation.isNew(entity)) {
        em.persist(entity);
        return entity;
    } else {
        return em.merge(entity);   // <-- this is your use case
    }
}

It will call em.merge(), which will return with whatever new underlying changes have been made to the record/entity in the database. So, you should check to see what else might be updating this entity in the background.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=239574&siteId=1