[英]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.