Spring Data JPA:使用规范实现自定义存储库行为

6
我想创建一个具有自定义行为的Spring Data JPA存储库,并使用规范实现该自定义行为。我已经阅读了Spring Data JPA文档,以实现单个存储库中的自定义行为来设置此项,但没有使用Spring Data 规范的示例。如果可能的话,怎么做呢?
我没有看到一种方法可以将接受规范的内容注入到自定义实现中。我认为我会很聪明地将存储库的CRUD部分注入到自定义部分中,但这会导致循环实例化依赖。
我没有使用QueryDSL。谢谢。
2个回答

5

我想主要的灵感来源可能是SimpleJpaRepository如何处理规范。值得关注的关键点包括:


2

我不确定这是否与您相关,因为它没有使用规范,但是我能够注入自定义行为的一种方法如下:

  1. Basic structure: as follows

    i. create a generic interface for the set of entity classes which are modeled after a generic parent entity. Note, this is optional. In my case I had a need for this hierarchy, but it's not necessary

    public interface GenericRepository<T> {
    
    // add any common methods to your entity hierarchy objects, 
    // so that you don't have to repeat them in each of the children entities
    // since you will be extending from this interface
    }
    

    ii. Extend a specific repository from generic (step 1) and JPARepository as

    public interface MySpecificEntityRepository extends GenericRepository<MySpecificEntity>, JpaRepository<MySpecificEntity, Long> {
    
    // add all methods based on column names, entity graphs or JPQL that you would like to 
    // have here in addition to what's offered by JpaRepository
    }
    

    iii. Use the above repository in your service implementation class

    1. Now, the Service class may look like this,

      public interface GenericService<T extends GenericEntity, ID extends Serializable> {
         // add specific methods you want to extend to user
      }
      
    2. The generic implementation class can be as follows,

      public abstract class GenericServiceImpl<T extends GenericEntity, J extends JpaRepository<T, Long> & GenericRepository<T>> implements GenericService<T, Long> {
      
      // constructor takes in specific repository
          public GenericServiceImpl(J genericRepository) {
             // save this to local var
          } 
        // using the above repository, specific methods are programmed
      
      }
      
    3. specific implementation class can be

      public class MySpecificEntityServiceImpl extends GenericServiceImpl<MySpecificEntity, MySpecificEntityRepository> implements MySpecificEntityService {
      
          // the specific repository is autowired
          @Autowired
          public MySpecificEntityServiceImpl(MySpecificEntityRepository genericRepository) {
               super(genericRepository);
               this.genericRepository = (MySpecificEntityRepository) genericRepository;
           }
       }
      

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接