Home > Enterprise >  Hibernate - extract function doesnt works anymore due to wrong type
Hibernate - extract function doesnt works anymore due to wrong type

Time:01-18

Since a migration to :

Spring boot : 3.0.1 Java 17: 3.0.1 Hibernate : 6.1.6 Dialect : Oracle 12c

@Column(name = "ALARM_DT")
    @Temporal(TemporalType.DATE)
    private Calendar date;
extract(day from (current_timestamp - alarm.date)) < 1

Unfortunately, this error message after the migration :


org.hibernate.QueryException: Parameter 2 of function extract() has type TEMPORAL, but argument is of type java.time.Duration

Does anyone have a solution for this? How Cast the result to date format.

Best regards

CodePudding user response:

The error is perfectly sensible and correct, and your query doesn't even make sense intuitively.

The difference between two timestamps (or in this case, between a timestamp and a date) is not another timestamp, it is a duration.

As an example: what is the difference between 25/3/72 and 23/3/74? The only sensible answer is "two days". Not some nonsensical date like 2/0/0 or something.

So, in HQL 6, the correct syntax for what you are trying to do is:

(current_date - alarm.date) by day < 1

Where:

  1. The expression current_date - alarm.date has Java type Duration, which is a quantity in nanoseconds.
  2. The operator by day serves to convert this nanosecond duration to an integer number of days.

This functionality is covered here:

https://docs.jboss.org/hibernate/orm/6.2/userguide/html_single/Hibernate_User_Guide.html#hql-Datetime-arithmetic

P.S. You should absolutely not be using Calendar to represent a datetime in 2023.

  • Related