这与以下问题是同一个问题:
如何根据用户的选择动态生成SQL查询?
唯一的区别是,我有兴趣看到也使用 Java/JPA(+可能是 EclipseLink 或 Hibernate 特定扩展)的解决方案。
我需要创建一个 GUI,用户可以使用它选择多个属性,这些属性将用于查询数据库以找到合适的人。我正在寻找如何根据用户的选择动态生成数据库查询的想法。
查询将包含多个字段,但为了了解这个想法,我将仅包含以下三个字段作为示例:
年龄参数在查询中是可选的。此外,用户可以指定年龄是否为必填参数。如果不是必需的,并且某人的个人资料中没有年龄,则该人的年龄标准将被忽略。
示例查询:
没有给出标准:
select * from persons
仅给出了职业:
select * from persons where occupation = 'dentist'
给出了几个职业:
select * from persons where (occupation = 'dentist' or occupation = 'engineer')
年龄被指定为大于值,并且它需要存在于人员的个人资料中:
select * from persons where age >= 30
身高已给出一个范围,并且不需要存在于人员的个人资料中:
select * from persons where (height is null or (height >= 30 and height <= 40))
不同标准的组合:
select * from persons where occupation = 'dentist' and age >= 30 and (height is null or (height >= 30 and height <= 40))
我已经实现了能够将查询生成为字符串的代码,但它肯定不太漂亮。我正在寻找实现这一目标的最有效和最漂亮的方法。