java – 具有多个参数的JPA Criteria API
作者:互联网
我需要创建一个使用带有多个参数的JPA Criteria API的搜索方法.
现在的问题是不是每个参数都是必需的.所以有些可能为null,它们不应包含在查询中.我已经用CriteriaBuilder尝试了这个,但我看不出如何让它工作.
使用Hibernate Criteria API,这非常简单.只需创建条件,然后添加限制.
Criteria criteria = session.createCriteria(someClass.class);
if(someClass.getName() != null) {
criteria.add(Restrictions.like("name", someClass.getName());
}
我怎么能用JPA的Criteria API实现同样的目标?
解决方法:
概念是构造javax.persistence.Predicate的数组,其中只包含我们想要使用的谓词:
要查询的示例实体:
@Entity
public class A {
@Id private Long id;
String someAttribute;
String someOtherAttribute;
...
}
查询本身:
//some parameters to your method
String param1 = "1";
String paramNull = null;
CriteriaBuilder qb = em.getCriteriaBuilder();
CriteriaQuery cq = qb.createQuery();
Root<A> customer = cq.from(A.class);
//Constructing list of parameters
List<Predicate> predicates = new ArrayList<Predicate>();
//Adding predicates in case of parameter not being null
if (param1 != null) {
predicates.add(
qb.equal(customer.get("someAttribute"), param1));
}
if (paramNull != null) {
predicates.add(
qb.equal(customer.get("someOtherAttribute"), paramNull));
}
//query itself
cq.select(customer)
.where(predicates.toArray(new Predicate[]{}));
//execute query and do something with result
em.createQuery(cq).getResultList();
标签:criteria-api,java,jpa 来源: https://codeday.me/bug/20190925/1817375.html