Java 将 CriteriaBuilder.between(Date) 添加到谓词?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41806152/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add CriteriaBuilder.between(Date) to Predicate?
提问by firstpostcommenter
I am new to JPA
我是 JPA 的新手
I am trying to query a table where my input date value should be between the startDate and endDate of the database record
我正在尝试查询一个表,其中我的输入日期值应该在数据库记录的 startDate 和 endDate 之间
I am trying to do:
我正在尝试做:
List<Predicate> conditionsList = new ArrayList<Predicate>();
conditionsList.add(criteriaBuilder.between(inputDate, root.get("startDate"), root.get("endDate")));
I found the below solution from Using JPA/Hibernate Criteria to pull between a date:
我从Using JPA/Hibernate Criteria to pull between a date 中找到了以下解决方案:
ParameterExpression<Date> d = criteriaBuilder.parameter(Date.class);
criteriaBuilder.between(d, root.<Date>get("startDate"), root.<Date>get("endDate"));
But how to set the Parameterexpression value to inputDate variable value before adding the CriteriaBuilder to the Predicate?
但是如何在将 CriteriaBuilder 添加到 Predicate 之前将 Parameterexpression 值设置为 inputDate 变量值?
回答by jonhid
Something like this should work...
这样的事情应该工作......
List<Predicate> conditionsList = new ArrayList<Predicate>();
Predicate onStart = criteriaBuilder.greaterThanOrEqualTo(root.get("startDate"), inputDate);
Predicate onEnd = criteriaBuilder.lessThanOrEqualTo(root.get("endDate"), inputDate);
conditionsList.add(onStart);
conditionsList.add(onEnd);
criteriaQuery.select(root).where(conditionsList.toArray(new Predicate[]{}));
回答by Gabriel Moreira
You can try this way.
你可以试试这个方法。
Predicate date = cb.between(root.get("date"), dateBefore, dateAfter); predicate.add(date);
this way works for my case.
这种方式适用于我的情况。
But for your case (using ParameterExpression).
但是对于您的情况(使用 ParameterExpression)。
return entityManager.createQuery(query) .setParameter(d, currentDate, TemporalType.DATE).getResultList();
When you create the query you set parameters.
currentDate
is your date,
d
is ParameterExpression
that you create before.
创建查询时,您可以设置参数。
currentDate
是你的日期,
d
是ParameterExpression
你之前创建的。
I prefer the first way, it is more intuitive and logical for me.
我更喜欢第一种方式,它对我来说更直观和合乎逻辑。
回答by Nelson Azevedo
Try this:
尝试这个:
criteriaBuilder.between(criteriaBuilder.literal(inputDate),
root.<Date>get("startDate"),
root.<Date>get("endDate"));