Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How spring data JPA decides to call entityManager.persist(…) or 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?

like image 288
Arghya Sadhu Avatar asked Dec 19 '14 19:12

Arghya Sadhu


1 Answers

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);
        }
    }

So it looks at entityInformation.isNew(entity). Implementation of this method is(in AbstractPersistable) :

public boolean isNew() {

        return null == getId();
    }

So it decides based on id field

like image 181
Elbek Avatar answered Oct 21 '22 21:10

Elbek