如何在 Spring Boot Data Jpa 应用程序中使用 Criteria Queries
我有一个使用 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);
}
我如何在 Spring Boot 应用程序中使用 Hibernate 为此类情况提供的 Criteria Query
How can i make use of Criteria Query that Hibernate provides for such cases in a Spring Boot Application
来自 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.
像这样定义一个接口
public interface StudentRepositoryCustom {
List<String> nameByCourse(String coursename);
}
然后像这样定义这个接口的自定义实现
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.
}
}
现在您可以像这样在 JPA 存储库中扩展此自定义存储库实现.
Now you can extend this custom repository implementaion in your JPA repository like so.
public interface StudentRepository extends CrudRepository<StudentEntity, Integer>, StudentRepositoryCustom {
}
了解有关条件查询和条件构建器的更多信息此处
一个>
Learn more about criteria query and criteria builder here