How to use Criteria Queries in Spring Boot Data Jpa Application

前端 未结 6 536
死守一世寂寞
死守一世寂寞 2020-12-04 23:10

I have an application that uses Spring Boot Data jpa . So far i am using a repository like this

public interface StudentRepository extends CrudRepos         


        
6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-04 23:54

    From the docs

    To enrich a repository with custom functionality you first define an interface and an implementation for the custom functionality. Use the repository interface you provided to extend the custom interface.

    Define an interface like so

    public interface StudentRepositoryCustom {
    
        List nameByCourse(String coursename);
    
    }
    

    Then define a custom implementation of this interface like so

    @Service
    class StudentRepositoryImpl implements StudentRepositoryCustom {
    
        @PersistenceContext
        private EntityManager em;
    
        public List nameByCourse(String coursename) {            
            CriteriaBuilder cb = em.getCriteriaBuilder();
            //Using criteria builder you can build your criteria queries.
        }
    
    }
    

    Now you can extend this custom repository implementaion in your JPA repository like so.

    public interface StudentRepository extends CrudRepository, StudentRepositoryCustom {
    
    }
    

    Learn more about criteria query and criteria builder here

提交回复
热议问题