首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JPL hibernate日期数学

JPL hibernate日期数学
EN

Stack Overflow用户
提问于 2011-12-01 23:22:25
回答 1查看 468关注 0票数 0

我是一个Java新手,在Spring中工作,使用我定制的Roo生成的模型。

我需要选择X天内具有"maturationDate“的特定类型(在本例中为租约)的记录。出于显示目的,我创建了一个执行数学运算的@Transient属性:

代码语言:javascript
复制
@Transient
private Integer daysToMaturation;

@PostLoad
public void postLoad() {
    Calendar calendar1 = Calendar.getInstance();
    Calendar calendar2 = Calendar.getInstance();

    calendar2.setTime(this.getMaturesDate());
    calendar1.setTime(new Date());

    long milis1 = calendar1.getTimeInMillis();
    long milis2 = calendar2.getTimeInMillis();

    long day = milis2 - milis1;

    Double diffDays = Math.ceil(day / (24 * 60 * 60 * 1000));

    this.daysToMaturation = diffDays.intValue();
}

这对于输出很好,但是现在我需要查找daysToMaturation <=的所有记录,很明显,这个属性直到查询之后才存在。

可悲的是,JPQL的日期函数非常原始。如果我可以得到原始的SQL (可能在@Formula字段中),我就可以用一行代码来解决这个问题。我真正想要的是这样说的能力:

代码语言:javascript
复制
@Formula("(select datediff(maturesDate, CURRENT_DATE())")
private Integer daysToMaturation;

...but失败了,大概是因为我没有对MySQL说datediff(),我是对JPA说的,它从来没有听说过它。它抛出以下异常:

代码语言:javascript
复制
org.hibernate.exception.SQLGrammarException: could not execute query; nested 
exception is javax.persistence.PersistenceException: 
org.hibernate.exception.SQLGrammarException: could not execute query

Hibernate记录以下行:

代码语言:javascript
复制
ERROR org.hibernate.util.JDBCExceptionReporter - You have an error in your SQL 
syntax; check the manual that corresponds to your MySQL server version for the 
right syntax to use near '' at line 1
EN

回答 1

Stack Overflow用户

发布于 2011-12-01 23:43:19

代码语言:javascript
复制
int daysToMaturation = 10;
Date maxDate = addDaysToCurrentDate(daysToMaturation);
String jpql = "select lease from Lease lease where lease.maturationDate <= :maxDate";
// ...
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8343744

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档