用于动态查询的 JPA Criteria 构建器

Ile*_*ski 4 c# java hibernate criteria-api

我必须编写一个方法,向它传递一些参数,并根据哪些参数为空,它修改我最后需要执行的查询。

Customer例如,如果我想从具有ID, name,的表中进行选择,surnameaddress起始查询将为SELECT * FROM Customer WHERE ID=myId AND name=myName AND surname=mySurname(现在我们检查我发送的地址是否为空,如果不是,则将其添加到查询中)。

我知道如何在 C# 中执行此操作,只需执行一个起始字符串,然后添加到其中并直接使用 ExecuteStoreQuery,但这在 Java 中会是什么样子呢?Criteria Builder 是一个可行的工具吗?

太感谢了!

csa*_*hof 5

使用 CriteriaQuery,可以执行类似的操作(使用静态 JPA 元模型类):

public List<Customer> findCustomer(Long myId, String myName, String mySurName, String myAddress) {
    CriteriaBuilder cb = enitityManager.getCriteriaBuilder();
    CriteriaQuery<Customer> query = cb.createQuery(Customer.class);
    Root<Customer> root = query.from(Customer.class);

    List<Predicate> predicates = new ArrayList<>();
    predicates.add(cb.equal(root.get(Customer_.ID), myId));
    predicates.add(cb.equal(root.get(Customer_.NAME), myName));
    predicates.add(cb.equal(root.get(Customer_.SURNAME), mySurName));

    if(address != null) {
        predicates.add(cb.equal(root.get(Customer_.ADDRESS), myAddress));
    }

    query.select(root).where(cb.and(predicates.toArray(new Predicate[0])));

    return entityManager.createQuery(query).getResultList();
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,只有在不存在的情况下才会检查该地址null

另一个不使用静态 JPA 元模型的示例(对此不是 100% 确定):

public List<Customer> findCustomer(Long myId, String myName, String mySurName, String myAddress) {
    CriteriaBuilder cb = enitityManager.getCriteriaBuilder();
    CriteriaQuery<Customer> query = cb.createQuery(Customer.class);
    Root<Customer> root = query.from(Customer.class);

    List<Predicate> predicates = new ArrayList<>();
    predicates.add(cb.equal(root.get("ID"), myId));
    predicates.add(cb.equal(root.get("name"), myName));
    predicates.add(cb.equal(root.get("surename"), mySurName));

    if(address != null) {
        predicates.add(cb.equal(root.get("address"), myAddress));
    }

    query.select(root).where(cb.and(predicates.toArray(new Predicate[0])));

    return entityManager.createQuery(query).getResultList();
}
Run Code Online (Sandbox Code Playgroud)