Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass date parameter to native query

A user can perform actions based on an occurrence value. When this value is equal to 'DAILY', I would like to retrieve all daily actions that have not been completed the last 24 hours.

The working SQL query:

SELECT distinct a.* FROM action as a LEFT OUTER JOIN history as h
ON a.id = h.action_id
AND h.user_id= <user> WHERE a.occurrence = 'DAILY' AND (h.id is NULL OR h.entry_date < TIMESTAMP 'yesterday')

The equivalent native query:

@Query(value = 
        "SELECT distinct a.* FROM action a "
        + "LEFT OUTER JOIN history h "
        + "ON a.id = h.action_id "
        + "AND h.user_id = :userId "
        + "WHERE a.occurrence='DAILY' AND (h.id IS NULL OR h.entry_date < :yesterday) ", nativeQuery = true)
public List<Action> findAllAvailableActions(@Param("userId") Long userId, @Param("yesterday") ZonedDateTime yesterday);

How it is called in my service :

ZonedDateTime today = ZonedDateTime.now(ZoneOffset.UTC);
ZonedDateTime yesterday = today.minus(1,ChronoUnit.DAYS);
Long userId = userDTO.getId();
List<Action> result = actionRepositoryCustom.findAllAvailableActions(userId, yesterday);

However, I do get the wrong results in my tests (actions that have already been completed are returned). I am afraid this is linked to the date parameter. The attribute entry_date is declared as ZoneDateTime in my entity. What am I doing wrong ?

hibernate : 5.2.4

like image 465
Is_sam Avatar asked Jul 03 '17 09:07

Is_sam


1 Answers

You can't pass a ZonedDateTime into a native SQL query. You need to convert it to Calendar:

@Query(value = 
    "SELECT distinct a.* FROM action a "
    + "LEFT OUTER JOIN history h "
    + "ON a.id = h.action_id "
    + "AND h.user_id = :userId "
    + "WHERE a.occurrence='DAILY' AND (h.id IS NULL OR h.entry_date < :yesterday)", nativeQuery = true)
public List<Action> findAllAvailableActions(@Param("userId") Long userId, @Param("yesterday") Calendar yesterday);

And you can convert your ZonedDateTime this way:

public Calendar convertToDatabaseColumn(ZonedDateTime entityAttribute) {
    if (entityAttribute == null) {
        return null;
    }

    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(entityAttribute.toInstant().toEpochMilli());
    calendar.setTimeZone(TimeZone.getTimeZone(entityAttribute.getZone()));
    return calendar;
}

This approach is described here: link

like image 98
dimirsen Z Avatar answered Oct 17 '22 02:10

dimirsen Z