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

后端 未结 5 703
眼角桃花
眼角桃花 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:23

    We use a custom Hibernate date type. Any time we set a parameter on a query we use a base class or utility method so we can pass the user's timezone into the custom type parameter.

    You could get by with just manually adjusting the time in the utility method for queries, but this way dates that are read in or written to the database are also correctly converted. This method also handles the situation where the database stores the date in its local time zone. So even if you have a user in one time zone, a database server in another, and Java using GMT, it can get everything straight. It ends up looking like:

    Properties properties = new Properties();
    properties.setProperty("timeZone", databaseTimeZone);
    query.setParameter("from", dateEnteredByUser, Hibernate.custom(LocalizedDateType.class, properties));
    

    As an added bonus, we use this to deal with the fact that SQL Server converts 23:59:59.999 to the next day. In the custom type we check for that and back it off.

提交回复
热议问题