How to add custom method to Spring Data JPA

后端 未结 12 1908
盖世英雄少女心
盖世英雄少女心 2020-11-22 12:58

I am looking into Spring Data JPA. Consider the below example where I will get all the crud and finder functionality working by default and if I want to customize a finder t

12条回答
  •  太阳男子
    2020-11-22 13:26

    If you want to be able to do more sophisticated operations you might need access to Spring Data's internals, in which case the following works (as my interim solution to DATAJPA-422):

    public class AccountRepositoryImpl implements AccountRepositoryCustom {
    
        @PersistenceContext
        private EntityManager entityManager;
    
        private JpaEntityInformation entityInformation;
    
        @PostConstruct
        public void postConstruct() {
            this.entityInformation = JpaEntityInformationSupport.getMetadata(Account.class, entityManager);
        }
    
        @Override
        @Transactional
        public Account saveWithReferenceToOrganisation(Account entity, long referralId) {
            entity.setOrganisation(entityManager.getReference(Organisation.class, organisationId));
            return save(entity);
        }
    
        private Account save(Account entity) {
            // save in same way as SimpleJpaRepository
            if (entityInformation.isNew(entity)) {
                entityManager.persist(entity);
                return entity;
            } else {
                return entityManager.merge(entity);
            }
        }
    
    }
    

提交回复
热议问题