Spring Data: Override save method

前端 未结 11 1283
温柔的废话
温柔的废话 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

    The solution from @ytterrr works but for older Spring Data versions, for Spring Data 2.1 at least, this is the way to not just override any repository method but also access to the underlying features (access to the entity manager to persist, delete, find...):

    public interface MyEntityRepositoryCustom {
       S save(S entity);
    }
    
    public class MyEntityRepositoryImpl implements MyEntityRepositoryCustom {
    
        final JpaEntityInformation entityInformation;
        EntityManager em;
    
        public MyEntityRepositoryImpl(EntityManager entityManager) {
            this.entityInformation = JpaEntityInformationSupport.getEntityInformation(MyEntity.class, entityManager);
            this.em = entityManager;
        }
    
        /**
         * @see org.springframework.data.jpa.repository.support.SimpleJpaRepository
         */
        @Transactional
        public  S save(S entity) {
    
            // do your logic here
    
            if (entityInformation.isNew(entity)) {
                em.persist(entity);
                return entity;
            } else {
                return em.merge(entity);
            }
        }
    }
    

提交回复
热议问题