具有多个参数的JPA Criteria API [英] JPA Criteria API with multiple parameters

查看:279
本文介绍了具有多个参数的JPA Criteria API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个使用带有多个参数的JPA Criteria API的搜索方法。
现在问题是不是每个参数都是必需的。因此有些可能为null,并且它们不应包含在查询中。我已经尝试过使用CriteriaBuilder,但我看不出如何使它工作。

I need to make a search method that uses the JPA Criteria API with multiple parameters. Now the problem is that not every parameter is required. So some could be null, and they shouldn't be included in the query. I've tried this with the CriteriaBuilder but I couldn't see how to make it work.

使用Hibernate Criteria API这很容易。只需创建条件,然后添加限制。

With the Hibernate Criteria API this is fairly easy. Just create the criteria and then add Restrictions.

Criteria criteria = session.createCriteria(someClass.class);
if(someClass.getName() != null) {
   criteria.add(Restrictions.like("name", someClass.getName());
}

我如何使用JPA的Criteria API实现相同的目标?

How could I achieve the same with JPA's Criteria API?

推荐答案

概念是构造 javax.persistence.Predicate ,其中只包含我们要使用的谓词:

Concept is to construct array of javax.persistence.Predicate which contains only predicates we want to use:

要查询的示例实体:

@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();

这篇关于具有多个参数的JPA Criteria API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆