gpt4 book ai didi

hibernate - 如何在 Spring Boot Data Jpa 应用程序中使用条件查询

转载 作者:行者123 更新时间:2023-12-04 01:24:40 24 4
gpt4 key购买 nike

我有一个使用 Spring Boot Data jpa 的应用程序。
到目前为止,我正在使用这样的存储库

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

最佳答案

来自 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.



像这样定义一个接口(interface)
public interface StudentRepositoryCustom {

List<String> nameByCourse(String coursename);

}

然后像这样定义这个接口(interface)的自定义实现
@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 存储库中扩展此自定义存储库实现。
public interface StudentRepository extends CrudRepository<StudentEntity, Integer>, StudentRepositoryCustom {

}

了解有关条件查询和条件构建器的更多信息 here

关于hibernate - 如何在 Spring Boot Data Jpa 应用程序中使用条件查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44278066/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com