简体   繁体   English

spring-data JpaRepository save() 方法副作用

[英]spring-data JpaRepository save() method side effect

I've noticed a very strange behavior with the save(T entity) in the spring-data JpaRepository.我注意到 spring-data JpaRepository 中的save(T entity)有一个非常奇怪的行为。

I have the entity Foo foo and I'm trying to save it with repository fooRepository.save(foo) .我有实体Foo foo并且我正在尝试使用存储库fooRepository.save(foo)保存它。 My issue is, the after saving, the instance of foo that I'm passing to the save() method is changed.我的问题是,保存后,我传递给save()方法的foo实例发生了变化。 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?这是预期的行为吗?

We can try to understand your observations by first checking the Javadoc for CrudRepository :我们可以通过首先检查CrudRepositoryJavadoc来尝试理解您的观察:

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:下面是save()方法的实际作用:

@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.它将调用em.merge() ,它将返回对数据库中的记录/实体所做的任何新的底层更改。 So, you should check to see what else might be updating this entity in the background.因此,您应该检查看看还有什么可能在后台更新此实体。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM