Spring数据JPA如何决定调用EntityManager.persist(…)或entityManager.merge(…)方法 [英] How spring data JPA decides to call entityManager.persist(…) or entityManager.merge(…) method
问题描述
在spring数据jpa中调用entityManager.persist(…)-方法时,以及在调用entityManager.merge(…)时.根据文档: 如果该实体尚未持久化,Spring Data JPA将通过调用entityManager.persist(...)-Method来保存该实体,否则将调用entityManager.merge(...)-Method ......
When entityManager.persist(…)-Method is called and when a entityManager.merge(…) is called in spring data jpa. According to documentation: If the entity has not been persisted yet Spring Data JPA will save the entity via a call to the entityManager.persist(…)-Method, otherwise the entityManager.merge(…)-Method will be called...
那么,弹簧数据如何确定实体是否持久?
So how does spring data determines whether the entity is persisted or not?
推荐答案
这是save
方法的含义(在SimpleJpaRepository
中):
here is the impl of save
method(in SimpleJpaRepository
):
/*
* (non-Javadoc)
* @see org.springframework.data.repository.CrudRepository#save(java.lang.Object)
*/
@Transactional
public <S extends T> S save(S entity) {
if (entityInformation.isNew(entity)) {
em.persist(entity);
return entity;
} else {
return em.merge(entity);
}
}
因此它看起来在entityInformation.isNew(entity)
上.此方法的实现是(在AbstractPersistable
中):
So it looks at entityInformation.isNew(entity)
. Implementation of this method is(in AbstractPersistable
) :
public boolean isNew() {
return null == getId();
}
所以它根据id字段决定
So it decides based on id field
这篇关于Spring数据JPA如何决定调用EntityManager.persist(…)或entityManager.merge(…)方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!