How to assign Date parameters to Hibernate query for current timezone?

后端 未结 5 548
眼角桃花
眼角桃花 2021-01-31 02:57

When you assign a date to a named SQL parameter Hibernate automatically converts it to GMT time. How do you make it use the current server timezone for all dates?

Lets s

5条回答
  •  醉酒成梦
    2021-01-31 03:25

    Hibernate team has deprecated setTimestamp(String name, Date val) method as well as org.hibernate.Query interface since version 5.2:

     /* @deprecated (since 5.2) use {@link #setParameter(int, Object)} or
        {@link #setParameter(int, Object, Type)}  instead
     */
    

    So you can use below code:

    import org.hibernate.query.Query;
    ...
    Query query = session.createQuery("from Table where date_field < :now");
    query.setParameter("now", new Date(), TimestampType.INSTANCE );
    

    It's notable that setDate method which cuts down time portion is also deprecated and can be replaced with this option(from the same interface org.hibernate.query.Query):

    query.setParameter("firstMomentOfToday", new Date(), DateType.INSTANCE);
    

    If you are going to use it with java 8 and the relevent jdbc drivers like Oracle 'ojdbc8.jar' and supported hibernate versions this might not work as expected, so it's wise to use new java.time.LocalDate and LocalDateTime instead.

提交回复
热议问题