【问题标题】:grails or hibernate criteria to search only by time componentgrails 或休眠条件仅按时间组件搜索
【发布时间】:2014-03-25 14:54:01
【问题描述】:

下面是我的域对象。

Game {
    Date startDate
}

现在我只想搜索从早上 hh:mm AM(动态搜索)开始的游戏,无论日期如何。我正在寻找类似这样的 Grails 标准

Game.where {
    startDate.timePart == timeValue
}.list()

其中 timeValue = "10:30 AM" 或类似的东西。

由于 GORM 不支持一些自定义限制,我正在使用 Hibernate 标准,所以如果有人知道如何使用 Hibernate 标准,那就太好了。

现在这是我在 Hibernate Criteria 中尝试做的事情,但它不起作用(我正在使用 postgre)。

searchCriteria.add(Restrictions.sqlRestriction("to_timestamp(start_date, 'h:mm a') = ? ", timeValue, StandardBasicTypes.DATE))

非常感谢您的帮助。

【问题讨论】:

    标签: hibernate grails grails-orm hibernate-criteria


    【解决方案1】:

    你可以得到一个只有时间的 Date 实例,并在 Hibernate Criteria API 中使用它来查询。

    Compare date's date part only with Timestamp in Hibernate

    【讨论】:

    • 如果我只用时间创建 Date 实例,它将无法工作,因为“startDate”是保存在数据库中的时间戳,仅与时间比较不会返回预期结果。
    【解决方案2】:

    您可以使用 HibernateCriteriaBuilder。 builder可以通过Grails领域类的“createCriteria()”动态静态方法来获取:

       def c = Game.createCriteria()
       def results = c {
         eq("start_date",timeValue)
       }
    

    构建器也可以使用 SessionFactory 和持久类实例独立实例化:

      new HibernateCriteriaBuilder(clazz, sessionFactory).list {
         eq("start_date", timeValue)
      }
    

    【讨论】:

    • @Fahimah - 非常感谢您的回复。如果我尝试使用您的实现,那么 grails 标准将尝试将“start_date”匹配为日期。我想要的是,只比较时间部分。在 GUI 中,用户将输入上午 10:30 之类的内容,我必须列出此时开始的所有游戏,无论日期如何。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-20
    • 2012-12-21
    • 2012-10-01
    • 2010-09-24
    相关资源
    最近更新 更多