简体   繁体   English

使用 JPA 的复杂查询

[英]Complex queries using JPA

I have a mySQL database that stores information about cities by zip code including dog population and cat population.我有一个 mySQL 数据库,它按邮政编码存储有关城市的信息,包括狗的数量和猫的数量。 I would like to query the database for all zip codes that have a higher dog population than cat population, and order the results by the difference in descending order.我想查询数据库中所有狗数量高于猫数量的邮政编码,并按降序对结果进行排序。

I'm using the JpaRepository class and have figured out how to create simple queries such as findByPopulation(int population) but is JPA capable of creating a complex query like the one I need?我正在使用 JpaRepository 类并且已经弄清楚如何创建简单的查询,例如findByPopulation(int population)但是 JPA 是否能够创建像我需要的那样的复杂查询?

You can use Spring JPA Specification to build complex query.您可以使用Spring JPA 规范来构建复杂的查询。

I am not sure about your relationship but as per my understanding.我不确定你们的关系,但根据我的理解。 Below code should be helpful.下面的代码应该会有所帮助。

 public static Specification<City> isDogsGreaterThanCats() {

return (root, query, cb) ->{ 

        return cb.greaterThan(root.get(dog_count), root.get(cat_count));

};

Repo method call will be like回购方法调用将像

cityRepository.findAll(isDogsGreaterThanCats());

I suggest add a native query to the repo.我建议向 repo 添加本机查询。

@Query(value="",nativeQuery = true)
findByPopulation(@Param("population") int population);

Add your complex query in the value=""value=""添加您的复杂查询

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM