spring data JPA 如何决定调用 entityManager.persist(...) 或 entityManager.merge(...) 方法 [英] How spring data JPA decides to call entityManager.persist(…) or entityManager.merge(…) method

查看:19
本文介绍了spring data JPA 如何决定调用 entityManager.persist(...) 或 entityManager.merge(...) 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 spring data jpa 中调用 entityManager.persist(…)-Method 和调用 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...

那么spring data是如何判断实体是否持久化的呢?

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 data JPA 如何决定调用 entityManager.persist(...) 或 entityManager.merge(...) 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆