Java 如何使用 JPQL 获取数据库时间?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1659030/
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
How to get the database time with JPQL?
提问by Max
with native SQL I get the database time with a statement like:
使用本机 SQL,我使用如下语句获取数据库时间:
SELECT CURRENT_TIMESTAMP
with JPQL I get the same result with:
使用 JPQL 我得到相同的结果:
SELECT CURRENT_TIMESTAMP
FROM Customer c
WHERE c.id=1
Is there a way to get rid of the last two lines?
有没有办法摆脱最后两行?
thanks,
谢谢,
采纳答案by Pascal Thivent
According to the JSR 220: Enterprise JavaBeans 3.0specifications:
根据JSR 220: Enterprise JavaBeans 3.0规范:
4.6.16 Functional Expressions
The Java Persistence query language includes the following built-in functions, which may be used in the WHERE or HAVING clause of a query.
If the value of any argument to a functional expression is null or unknown, the value of the functional expression is unknown.
[...]
4.6.16.3 Datetime Functions
functions_returning_datetime:= CURRENT_DATE | CURRENT_TIME | CURRENT_TIMESTAMP
The datetime functions return the value of current date, time, and timestamp on the database server.
4.6.16 函数表达式
Java Persistence 查询语言包括以下内置函数,可以在查询的 WHERE 或 HAVING 子句中使用。
如果函数表达式的任何参数的值为空或未知,则函数表达式的值是未知的。
[...]
4.6.16.3 日期时间函数
functions_returning_datetime:= CURRENT_DATE | CURRENT_TIME | CURRENT_TIMESTAMP
datetime 函数返回数据库服务器上的当前日期、时间和时间戳的值。
So I'm already surprised you can write the 2nd form that is not correct per specification and might thus not be portable.
因此,我已经很惊讶您可以编写根据规范不正确的第二种形式,因此可能无法移植。
To me, the "right" way to do this would be to create a class with a date field of type java.util.Date
and to populate it with a native query. Something like that:
对我来说,执行此操作的“正确”方法是创建一个具有日期字段类型的类java.util.Date
并使用本机查询填充它。类似的东西:
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Entity
public class DateItem {
private Date date;
/**
* @return the date
*/
@Id
@Column(name = "DATE_VALUE")
@Temporal(TemporalType.TIMESTAMP)
public Date getDate() {
return date;
}
/**
* @param date
* the date to set
*/
public void setDate(Date date) {
this.date = date;
}
}
And then:
进而:
@PersistenceContext
EntityManager em;
/**
* @return System date on DB server
*/
public Date getSystemDate() {
Query query = em.createNativeQuery(
"SELECT CURRENT_TIMESTAMP", DateItem.class);
DateItem dateItem = (DateItem) query.getSingleResult();
return dateItem.getDate();
}