Using HQL to query on a date while ignoring the time on Oracle

后端 未结 4 1094
暖寄归人
暖寄归人 2020-12-06 04:59

I have a table (in Oracle 9 and up) where I need to find all entries for a given day using Hibernate. The entries have timestamps (with data type \'date\'). Some of the entr

4条回答
  •  不知归路
    2020-12-06 05:42

    I think there are two ways to solve this:

    1. Use a criteria query and add a SQLRestriction. The restriction would take the form "trim({alias}.date) = ?". A problem here could be the conversion of the input parameter to the correct type on Oracle (or other DBMS). You can provide the necessary (hibernate) type as parameter, but if this is database dependent, it will be hardcoded.

    2. use a formula in your hibernate mapping. The mapping would be:

        
          
        

    You can now use Hibernate's typing system to use a compare with a java object like this:

    s.createCriteria(Person.class)
     .add(Restrictions.eq("birthDay", new java.sql.Date(System.currentTimeMillis())))
     .list()
    

    One problem you'll have with both solutions is the trim function might not be available in the database. A solution for this (e.g. while testing on HSQLDB) is to put a import.sql on your classpath test (this will be picked up by Hibernate automatically) and create a procedure or function there. You can also Alter table Person add column birthDay timestamp in that file to make the generated schema work.

提交回复
热议问题