如何在Spring Boot Data Jpa应用程序中使用Criteria查询
我有一个使用 Spring Boot Data jpa 的应用程序。
到目前为止,我正在使用这样的存储库
I have an application that uses Spring Boot Data jpa . So far i am using a repository like this
public interface StudentRepository extends CrudRepository<StudentEntity, Integer>{
@Query(value = ""
+ "SELECT s.studentname "
+ "FROM studententity s, "
+ " courseentity c "
+ "WHERE s.courseid = c.courseid "
+ " AND s.courseid IN (SELECT c.courseid "
+ " FROM courseentity c "
+ " WHERE c.coursename = ?1)")
List<String> nameByCourse(String coursename);
}
如何使用 Criteria Query Hibernate在Spring Boot应用程序中提供这种情况
How can i make use of Criteria Query That Hibernate Provides for such cases in a Spring Boot Application
从 docs
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<String> nameByCourse(String coursename);
}
然后像这样定义这个接口的自定义实现 p>
Then define a custom implementation of this interface like so
@Service
class StudentRepositoryImpl implements StudentRepositoryCustom {
@PersistenceContext
private EntityManager em;
public List<String> 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<StudentEntity, Integer>, StudentRepositoryCustom {
}
详细了解条件查询和条件生成器 here
Learn more about criteria query and criteria builder here