Spring Data: Override save method

前端 未结 11 1263
温柔的废话
温柔的废话 2020-11-27 05:30

I\'m considering spring data for a project. Is it possible to override the per default generated save method? And if yes, how?

11条回答
  •  无人及你
    2020-11-27 05:43

    This could be helpful if you are going to reuse the original method. Just inject EntityManager in the implementing class.

    public interface MyEntityRepositoryCustom {
       S save(S entity);
    }
    
    public class MyEntityRepositoryImpl implements MyEntityRepositoryCustom {
    
        // optionally specify unitName, if there are more than one
        @PersistenceContext(unitName = PRIMARY_ENTITY_MANAGER_FACTORY)
        private EntityManager entityManager;
    
        /**
         * @see org.springframework.data.jpa.repository.support.SimpleJpaRepository
         */
        @Transactional
        public  S save(S entity) {
            // do your logic here
            JpaEntityInformation entityInformation = JpaEntityInformationSupport.getMetadata(MyEntity.class, entityManager);
            if (entityInformation.isNew(entity)) {
                entityManager.persist(entity);
                return entity;
            } else {
                return entityManager.merge(entity);
            }
        }
    }
    

提交回复
热议问题