简体   繁体   中英

grails or hibernate criteria to search only by time component

Given below is my Domain object.

Game {
    Date startDate
}

Now I want to only search the games which start at hh:mm AM (dynamic search) in the morning regardless of date. I am looking for Grails criteria something like this

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

Where timeValue = "10:30 AM" or anything like that.

I am using Hibernate criteria due to some custom restrictions that aren't support in GORM, so it would be nice if anyone knows how to do it with Hibernate criteria.

Right now this is what I am trying to do in Hibernate Criteria and it doesn't work(I am using postgre).

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

Highly appreciate your help.

You can use HibernateCriteriaBuilder. The builder can be retrieved through the "createCriteria()" dynamic static method of Grails domain classes:

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

The builder can also be instantiated standalone with a SessionFactory and persistent Class instance:

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

You can get a Date instance with only time and use that in Hibernate Criteria API to query.

Compare date's date part only with Timestamp in Hibernate

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM