【问题标题】:How to search current date in Timestamp field of MYSQL using Hibernate Named Query (HQL)?如何使用 Hibernate Named Query (HQL) 在 MYSQL 的时间戳字段中搜索当前日期?
【发布时间】:2017-10-18 09:55:33
【问题描述】:

我尝试使用以下方式传递日期但无法成功。 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

方式2:设置内置参数

@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

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

【问题讨论】:

  • 您在第一个示例中收到哪些错误消息?
  • @olegsv 没有收到任何数据..

标签: mysql hibernate jpa named-query


【解决方案1】:

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

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

由于基础类型是日期时间,所以我们需要将其转换为日期才能使用 current_date()

【讨论】:

    【解决方案2】:

    您需要指定时间类型。

    方式 1

    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 ;
    }
    

    【讨论】:

    • 谢谢,看起来很有希望,但它也不起作用,因为默认 bean 是 @Column(name = "ANTAS_AVSLUTTES") public Date getDateAnswered () { return dateAnswered ;我不能在这个实体上提到 TemporalType,因为在 MYSQL 中它是 DateTime 数据类型。
    • 无法编辑上述评论:抱歉,这里的列名是 @Column(name = "DATE_ANASWERED")
    • 好吧,我的错误是 TemporalType 需要是 DateTime 数据类型的 TIMESTAMP,所以我更新了我的答案
    猜你喜欢
    • 2013-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多