简体   繁体   English

如何使用JPA获取动态Where子句的数据

[英]How to fetch Data using JPA for dynamic Where Clause

I am new to JPA. 我是JPA的新手。 I am currently using JPA2.0 in WAS 8.5.5 我目前在WAS 8.5.5中使用JPA2.0

I have a search screen where we have lot of search criteria's. 我有一个搜索屏幕,其中有很多搜索条件。 Now, I have to create Query in JPA such a way that any criteria user has selected, it automatically check for that particular column in DB. 现在,我必须在JPA中创建查询,以便用户选择任何条件,它会自动检查数据库中的特定列。

I am not able to find any solution on that. 我无法找到任何解决方案。 It seems to me that for every search criteria, I have to write new named Query. 在我看来,对于每个搜索条件,我都必须编写新的命名查询。

Any suggestion or pointers will be appreciated. 任何建议或指示,将不胜感激。

You could do it in named query, but you would have to check every single possible criteria if it is null in order to avoid null values affect the results. 您可以在命名查询中执行此操作,但是您必须检查每个可能的条件是否为空,以避免空值影响结果。 Beware of unnecessary inner joins, each nullable relation should be included as left join 当心不必要的内部联接,每个可为空的关系都应作为左联接包括在内

select e from Employee e left join e.department d
where (:name is null or e.name = :name)
  and (:email is null or e.email = :email)
  and (:deptId is null or d.id = :deptId)
...

However, depending on complexity of possible combinations, better option could be to not use named queries, but dynamically construct a JPQL depending on selected criteria. 但是,根据可能的组合的复杂性,更好的选择可能是不使用命名查询,而是根据所选条件动态构建JPQL。

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

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