Search code examples
javaspringspring-data-jpaspring-repositories

Using EntityManager on top of Spring Data Repositories


Recently, I came across the following piece of code:

@Transactional
public MyEntity insert(MyEntity entity) {
    MyEntity merged = entityManager.merge(entity);
    return myEntityRepository.save(merged);
}

where entity manager is defined as follows:

@PersistenceContext private EntityManager entityManager;

and repository is Spring QueryDSL repository:

@Repository
public interface MyEntityRepository extends QueryDslRepository<MyEntity>{
}

My question is, whether is it really necessary to call entityManager.merge(entity) when we are persisting the entity using the myEntityRepository right after? Is there something the entityManager is doing that the repository cannot? Shouldn't calling the repository be enough?


Solution

  • That looks like cargo cult programming to me. The implementation of save() already does a merge if necessary (and sometimes when it isn't necessary):

    /*
     * (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);
        }
    }