How to add custom method to Spring Data JPA

后端 未结 12 2021
盖世英雄少女心
盖世英雄少女心 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:37

    As specificed in the documented functionality, the Impl suffix allows us to have a clean solution:

    • Define in the @Repository interface, say MyEntityRepository, either Spring Data methods or custom methods
    • Create a class MyEntityRepositoryImpl (the Impl suffix is the magic) anywhere (doesn't even need to be in the same package) that implements the custom methods only and annotate such class with @Component** (@Repository will not work).
      • This class can even inject MyEntityRepository via @Autowired for use in the custom methods.


    Example:

    Entity class:

    package myapp.domain.myentity;
    
    @Entity
    public class MyEntity {
    
        @Id
        private Long id;
    
        @Column
        private String comment;
    
    }
    

    Repository interface:

    package myapp.domain.myentity;
    
    @Repository
    public interface MyEntityRepository extends JpaRepository {
    
        // EXAMPLE SPRING DATA METHOD
        List findByCommentEndsWith(String x);
    
        List doSomeHql(Long id);
    
        List useTheRepo(Long id);
    
    }
    

    Custom methods implementation bean:

    package myapp.infrastructure.myentity;
    
    @Component // Must be @Component !!
    public class MyEntityRepositoryImpl { // must have the repo name + Impl !!
    
        @PersistenceContext
        private EntityManager entityManager;
    
        @Autowired
        private MyEntityRepository myEntityRepository;
    
        @SuppressWarnings("unused")
        public List doSomeHql(Long id) {
            String hql = "SELECT eFROM MyEntity e WHERE e.id = :id";
            TypedQuery query = entityManager.createQuery(hql, MyEntity.class);
            query.setParameter("id", id);
            return query.getResultList();
        }
    
        @SuppressWarnings("unused")
        public List useTheRepo(Long id) {
            List es = doSomeHql(id);
            es.addAll(myEntityRepository.findByCommentEndsWith("DO"));
            es.add(myEntityRepository.findById(2L).get());
            return es;
        }
    
    }
    

    The small drawbacks I identified are:

    • The custom methods in the Impl class are marked as unused by the compiler, thus the @SuppressWarnings("unused") suggestion.
    • You have a limit of one Impl class. (Whereas in the regular fragment interfaces implementation the docs suggest you could have many.)

提交回复
热议问题