[英]JPA Criteria builder for dynamic query
I have to write a method where I pass it some arguments and depending on which arguments are empty it modifies the query I need to execute at the end.我必须编写一个方法,在其中传递一些 arguments 并根据哪个 arguments 为空,它会修改我需要在最后执行的查询。
Eg if I want to select from a table Customer
that has an ID
, name
, surname
and address
the starting query would be SELECT * FROM Customer WHERE ID=myId AND name=myName AND surname=mySurname
(and now we check if the address I sent is empty, if it is NOT, add it to the query).例如,如果我想 select 从具有
ID
、 name
、 surname
和address
的表Customer
开始查询将是SELECT * FROM Customer WHERE ID=myId AND name=myName AND surname=mySurname
(现在我们检查地址是否 I sent 为空,如果不是,则将其添加到查询中)。
I know how to do this in C#, by simply doing a starting string and then just adding to it and using ExecuteStoreQuery directly, but how would this look in Java?我知道如何在 C# 中执行此操作,只需执行一个起始字符串,然后添加到它并直接使用 ExecuteStoreQuery,但是这在 Java 中会如何? Is Criteria Builder a viable tool for this?
Criteria Builder 是一个可行的工具吗?
Thank you so much!太感谢了!
Using a CriteriaQuery, it is possible to do something like that (using Static JPA Metamodel Classes):使用 CriteriaQuery,可以执行类似的操作(使用 Static 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();
}
In this case, the address will only be checked if it is not null
.在这种情况下,只有不是
null
时才会检查地址。
Another example without using Static JPA Metamodel (not 100% sure about this):另一个不使用 Static 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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.