简体   繁体   English

使用Spring数据JPA,如何为过滤器表单创建动态查询

[英]Using Spring data JPA, how can I create a dynamic query for a filter form

I want to create a form that will generate the sql query for me based on the form input. 我想创建一个表单,该表单将根据表单输入为我生成sql查询。

For example, I have a table People[id, name, age], and a form with two fields: Name and age. 例如,我有一个表People [id,name,age],以及一个包含两个字段的表单:Name和age。

If all the two fields are completed on the form, the query was going to be like this: 如果在表单上完成了所有两个字段,则查询将如下所示:

 List<People> findByNamendAge(String name, Int age);

But if only the name is filled, I want to show all the people that correspond to just the name, even though the age is left blank. 但是,如果只填写姓名,即使年龄留为空白,我也想显示与姓名相对应的所有人员。

(of course, in this example I could create a findByName(String name) and a finByAge(Int age) , and a simple if/else would do, but my real problem envolves a filter that contains a large amount of inputs) (当然,在此示例中,我可以创建一个findByName(String name)finByAge(Int age) ,以及一个简单的if / else都可以,但是我真正的问题是包含大量输入的过滤器)

You should use JPA CriteriaAPI for that. 您应该为此使用JPA CriteriaAPI。 You can find an example here: 您可以在此处找到示例:

Conditional where clause in JPA criteria query JPA条件查询中的条件where子句

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

相关问题 使用Spring Data JPA,如何创建具有多个条件或在同一字段上或的查询? - Using Spring Data JPA, how can I create a query with multiple conditions ORed on same field? Spring 数据 JPA - 创建动态查询注释 - Spring Data JPA - Create a dynamic Query annotation 我如何创建一个自定义查询与 Spring 数据 JPA 共享字段? - how can i create a Custom Query with Spring Data JPA with shared fields? 使用Spring数据Jpa时如何使用大脚本查询数据? - How can I use large a script to query data when using Spring Data Jpa? 使用Spring JPA查询过滤数据 - Filter Data with Spring JPA Query 如何在 Spring Data jpa 中应用本机连接查询? - How can i apply native join query in spring data jpa? Spring 数据 JPA - 如何使用嵌入式实体进行 existsBy 查询? - Spring Data JPA - How can I make a existsBy query using an embedded entity? 如何使用带有“从方法名创建查询”策略的Spring数据JPA来实现这两个简单查询? - How can I implement these 2 simple queries using Spring data JPA with the “query creation from method names” strategy? 如何使用 Spring Data ORM/JPA 延迟创建 EntityManagerFactory? - How can I lazy create the EntityManagerFactory using Spring Data ORM/JPA? 在 Spring 数据 JPA 中使用 @Query 进行动态查询? - Dynamic query with @Query in Spring Data JPA?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM