如何使用 Hibernate 命名查询 (HQL) 在 MYSQL 的时间戳字段中搜索当前日期?

How to search current date in Timestamp field of MYSQL using Hibernate Named Query (HQL)?

我尝试使用以下方式传递日期但无法成功。 dateAnswered 是将日期存储为 2017-09-13 00:00:00.

的字段

谁能告诉我哪里错了:

方式一:设置参数

@NamedQuery(name = "findAnswar", query = "SELECT a FROM Answar a WHERE (a.dateAnswered = :currentDate )"

Try 1: 
super.em.createNamedQuery( "findAnswar" , Answar .class ).setParameter( "currentDate", new Date() ); //Not receive any data

Try 2: 
Date date = new Date();
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
super.em.createNamedQuery( "findAnswar" , Answar .class ).setParameter( "currentDate",  date) //Not receive any data

方式二:设置内置参数

@NamedQuery(name = "findAnswar", query = "SELECT a FROM Answar a WHERE (a.dateAnswered = current_date() )") //NOT WORKS

It works if i do add Temporal to getter:

@Column(name = "DATE_ANASWERED")
@Temporal(TemporalType.DATE)
 public Date getDateAnswered () {
  return dateAnswered ;
}

BUT IT GIVES another issue : Caused by: org.hibernate.HibernateException: Wrong column type in db.ANSWAR for column DATE_ANASWERED. Found: datetime, expected: date

 @NamedQuery(name = "findAnswar", query = "SELECT a FROM Answar a WHERE (a.dateAnswered = current_date )") //NOT WORKS - JPA errors

即使在 Whosebug 的先前答案中,我也找不到任何相关的解决方案。任何人都可以仅使用命名查询来帮助修复相同问题吗?

您需要指定时间类型。

方式一

super.em.createNamedQuery("findAnswar", Answar.class)
     .setParameter("currentDate", new Date(), TemporalType.TIMESTAMP);

方式 2

@Column(name = "DATE_ANASWERED")
@Temporal(TemporalType.TIMESTAMP)
    public Date getDateAnswered () {
    return dateAnswered ;
}

能够通过对命名查询进行以下更改来实现它,并且效果很好:

"SELECT a FROM Answar a WHERE cast(a.dateAnswered as date) = current_date()

由于底层类型是 datetime 所以我们需要将它转换为 date 才能使用 current_date()