调用 CriteriaQuery 方法使用 add_months 甲骨文方法。

huangapple go评论54阅读模式
英文:

Call oracle method add_months using CriteriaQuery

问题

我有一个查询,我想使用 CriteriaQuery 来执行。

查询:

select * from MY_TABLE where updated_at <= add_months(TRUNC(SYSDATE) + 1, -3)

基本上是在表中查找所有 update_at 日期早于3个月的记录。

我尝试了这个博客中介绍的方法。

问题是我有一个参数 -3,但我期望的返回类型是 Date

代码:

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery cq = cb.createQuery(MyTable.class);
Root<MyTable> root = cq.from(MyTable.class);
Expression<Date> truncExpr = cb.function("TRUNC", Date.class, cb.currentTimestamp());
Expression<Date> addMonthsExpr = cb.function("add_months", Date.class, truncExpr, months); // <----Compilation error.
Predicate datePredicate = cb.lessThanOrEqualTo(root.get("updated_at"), addMonthsExpr);

请提供建议。

英文:

I've a query that I would like to execute using CriteriaQuery.

Query:

select * from MY_TABLE where updated_at &lt;= add_months(TRUNC(SYSDATE) + 1, -3)

It is basically finding all records in table whose update_at date is earlier than 3 months.

I tried the approach presented at this blog.

Issue is I've -3 as the parameter, but my expected return type is Date.

Code:

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery cq = cb.createQuery(MyTable.class);
Root&lt;MyTable&gt; root = cq.from(MyTable.class);
Expression&lt;Date&gt; truncExpr = cb.function(&quot;TRUNC&quot;, Date.class, cb.currentTimestamp());
Expression&lt;Date&gt; addMonthsExpr = cb.function(&quot;add_months&quot;, Date.class, truncExpr, months); // &lt;----Compilation error.
Predicate datePredicate = cb.lessThanOrEqualTo(root.get(&quot;updated_at&quot;), addMonthsExpr);

Please suggest.

答案1

得分: 1

months变量的定义没有显示,但我猜它是一个整数,例如:

int months = -3; // 或者从方法参数中获取,类型为int

正确的方法如下(除非你知道这个方法,否则不太直观):

Expression<Integer> months = cb.literal(-3);
英文:

The definition of the months variable is not displayed, but my guess is that it is an integer, e.g.:

int months = -3; // or from a method argument of type int anyway

The correct way is the following (unintuitive unless you know about it):

Expression&lt;Integer&gt; months = cb.literal(-3);

huangapple
  • 本文由 发表于 2020年9月2日 05:00:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/63695389.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定