[英]JPQL check in parameter not null and then execute query
I have some parameters which can be null or can be not null. 我有一些参数可以为null或不能为null。
What I want to do is to execute query only with parameters which are not null. 我想要做的是只使用非null的参数执行查询。
For example I have: 例如,我有:
String param1;
String param2;
And I want to do something like this: 我想做这样的事情:
If ( param1 != null && param2 != null ) {
Query q = em.createQuery("SELECT a FROM Advert where a.property = param1 and a.property2= param2);
}
if( param1 == null && param2 != null ) {
Query q = em.createQuery("SELECT a FROM Advert where a.property2= param2")
}
if( param1 != null && param2 == null ) {
Query q = em.createQuery("SELECT a FROM Advert where a.property= param1");
}
Is it possible to do this not using if statements but with jpql query string? 有可能不使用if语句而是使用jpql查询字符串吗? ( because I have more than two parameters and it is not so convenient to check so many cases)
(因为我有两个以上的参数,检查这么多情况不太方便)
You can have something like this : 你可以这样:
CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
CriteriaQuery<Advert> query = criteriaBuilder.createQuery(Advert.class);
Root<Advert> advertRoot = query.from(Advert.class);
query.select(advertRoot);
List<Predicate> criteria = new ArrayList<Predicate>();
if(property != null){
ParameterExpression<String> p =
criteriaBuilder.parameter(String.class, "property");
criteria.add(criteriaBuilder.equal(advertRoot.get("property"), p));
}
if(property1 != null){
ParameterExpression<String> p =
criteriaBuilder.parameter(String.class, "property1");
criteria.add(criteriaBuilder.equal(advertRoot.get("property1"), p));
}
if (criteria.size() == 0) {
throw new RuntimeException("no criteria");
} else if (criteria.size() == 1) {
query.where(criteria.get(0));
} else {
query.where(criteriaBuilder.and(criteria
.toArray(new Predicate[0])));
}
TypedQuery<Advert> q = em.createQuery(query);
//set your query parameters here
if (property != null) { q.setParameter("property", property); }
if (property1 != null) { q.setParameter("property1", property1); }
List<Advert> resultList = q.getResultList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.