Skip to content

Instantly share code, notes, and snippets.

@freitzzz
Last active June 22, 2018 01:01
Show Gist options
  • Save freitzzz/723c06e7a4c4ce193991482b3c9a2faf to your computer and use it in GitHub Desktop.
Save freitzzz/723c06e7a4c4ce193991482b3c9a2faf to your computer and use it in GitHub Desktop.
JPA LocalDateTime Queries

In JPA 2.1 to compare dates as LocalDateTimes, there is need to use the SQL function "CAST" on the JPQL Query

Example:

  • We want to retrieve the number of actions occured on a certain System during a period of time

The entity:


@Entity
class SystemAction{
  /**
   * LocalDateTime with the date which the action occured
   */
  private LocalDateTime actionDate;
}

The function:


public long getActionsOccurencesOnPeriodOfTime(LocalDateTime dateX,LocalDateTime dateY){
  return entityManager.createQuery("SELECT COUNT(SA) FROM SystemAction SA WHERE CAST(SA.actionDate as timestamp) BETWEEN :dateX AND :dateY")
                                  .setParameter("dateX",dateX)
                                  .setParameter("dateY",dateY)
                                  .getSingleResult();
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment