Close

JPA Criteria API - CriteriaBuilder Date Time Operations

[Updated: Mar 7, 2019, Created: Mar 7, 2019]

The following methods of CriteriaBuilder can be used for date/time/timestamp operations:

package javax.persistence.criteria;
 ........
public interface CriteriaBuilder {
    ........
    //Create expression to return current date.
    Expression<java.sql.Date> currentDate();

    //Create expression to return current timestamp.
    Expression<java.sql.Timestamp> currentTimestamp();

    //Create expression to return current time.
    Expression<java.sql.Time> currentTime();
	........
}

Also check out JPQL date time functions.

Example

Entity

@Entity
public class ScheduledEvent {
  @Id
  @GeneratedValue
  private long id;
  private String eventName;
  private Date date;
  private Time start;
  private Time end;
  private Timestamp eventCreated;
    .............
}

Performing date time operations

public class ExampleMain {
  private static EntityManagerFactory entityManagerFactory =
          Persistence.createEntityManagerFactory("example-unit");

  public static void main(String[] args) {
      try {
          persistEvent();
          findCurrentEvent();
          findTodayEvent();
          findEventCreatedNow();
      } finally {
          entityManagerFactory.close();
      }
  }

  private static void findCurrentEvent() {
      System.out.println("-- current ongoing event  --");
      EntityManager entityManager = entityManagerFactory.createEntityManager();
      CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
      CriteriaQuery<ScheduledEvent> query = criteriaBuilder.createQuery(ScheduledEvent.class);
      Root<ScheduledEvent> scheduledEventRoot = query.from(ScheduledEvent.class);
      Predicate scheduleDatePredicate = criteriaBuilder
              .equal(scheduledEventRoot.get(ScheduledEvent_.DATE), criteriaBuilder.currentDate());
      Predicate scheduleTimePredicate = criteriaBuilder
              .between(criteriaBuilder.currentTime(), scheduledEventRoot.get(ScheduledEvent_.start),
                      scheduledEventRoot.get(ScheduledEvent_.end));
      query.select(scheduledEventRoot)
           .where(criteriaBuilder.and(scheduleDatePredicate, scheduleTimePredicate));
      //The equivalent JPQL:
      //SELECT e FROM ScheduledEvent e WHERE CURRENT_DATE = e.date AND
      // CURRENT_TIME BETWEEN e.start AND e.end

      List<ScheduledEvent> resultList = entityManager.createQuery(query).getResultList();
      resultList.forEach(System.out::println);
      entityManager.close();
  }

  private static void findTodayEvent() {
      System.out.println("-- today event  --");
      EntityManager entityManager = entityManagerFactory.createEntityManager();
      CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
      CriteriaQuery<ScheduledEvent> query = criteriaBuilder.createQuery(ScheduledEvent.class);
      Root<ScheduledEvent> scheduledEventRoot = query.from(ScheduledEvent.class);
      query.select(scheduledEventRoot)
           .where(criteriaBuilder.equal(
                   scheduledEventRoot.get(ScheduledEvent_.date),
                   criteriaBuilder.currentDate()
                   )
           );

      List<ScheduledEvent> resultList = entityManager.createQuery(query).getResultList();
      resultList.forEach(System.out::println);
      entityManager.close();
      //The equivalent JPQL:
      //SELECT e FROM ScheduledEvent e WHERE CURRENT_DATE = e.date
  }

  private static void findEventCreatedNow() {
      System.out.println("-- event created within 10 sec --");
      EntityManager entityManager = entityManagerFactory.createEntityManager();
      CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
      CriteriaQuery<ScheduledEvent> query = criteriaBuilder.createQuery(ScheduledEvent.class);
      Root<ScheduledEvent> scheduledEventRoot = query.from(ScheduledEvent.class);
      query.select(scheduledEventRoot)
           .where(criteriaBuilder.between(
                   scheduledEventRoot.get(ScheduledEvent_.eventCreated),
                   criteriaBuilder.literal(Timestamp.valueOf(LocalDateTime.now().minusSeconds(10))),
                   criteriaBuilder.currentTimestamp())
           );
      //The equivalent JPQL:
      //SELECT e FROM ScheduledEvent e WHERE e.eventCreated
      // BETWEEN :timestampStart AND CURRENT_TIMESTAMP
      // where timestampStart = Timestamp.valueOf(LocalDateTime.now().minusSeconds(10)))

      List<ScheduledEvent> resultList = entityManager.createQuery(query).getResultList();
      resultList.forEach(System.out::println);
      entityManager.close();
  }

  private static void persistEvent() {
      ScheduledEvent e1 = ScheduledEvent.create("Test event",
              LocalDate.of(2018, 6, 1),
              LocalTime.of(9, 30, 45),
              LocalTime.of(11, 45, 30),
              LocalDateTime.now().minusDays(10));

      ScheduledEvent e2 = ScheduledEvent.create("Test event2",
              LocalDate.now(),
              LocalTime.of(9, 30, 45),
              LocalTime.of(23, 45, 30),
              LocalDateTime.now().minusMonths(1));

      ScheduledEvent e3 = ScheduledEvent.create("Test event3",
              LocalDate.now(),
              LocalTime.of(18, 0, 0),
              LocalTime.of(20, 0, 0),
              LocalDateTime.now());

      EntityManager em = entityManagerFactory.createEntityManager();
      em.getTransaction().begin();
      em.persist(e1);
      em.persist(e2);
      em.persist(e3);
      em.getTransaction().commit();

      System.out.println("-- all persisted entities --");
      em.createQuery("SELECT e FROM ScheduledEvent e")
        .getResultList()
        .forEach(System.out::println);
      em.close();
  }
}
-- all persisted entities --
ScheduledEvent{id=1, eventName='Test event', date=2018-06-01, start=09:30:45, end=11:45:30, eventCreated=2019-02-25 23:28:37.711}
ScheduledEvent{id=2, eventName='Test event2', date=2019-03-07, start=09:30:45, end=23:45:30, eventCreated=2019-02-07 23:28:37.715}
ScheduledEvent{id=3, eventName='Test event3', date=2019-03-07, start=18:00:00, end=20:00:00, eventCreated=2019-03-07 23:28:37.715}
-- current ongoing event --
ScheduledEvent{id=2, eventName='Test event2', date=2019-03-07, start=09:30:45, end=23:45:30, eventCreated=2019-02-07 23:28:37.715}
-- today event --
ScheduledEvent{id=2, eventName='Test event2', date=2019-03-07, start=09:30:45, end=23:45:30, eventCreated=2019-02-07 23:28:37.715}
ScheduledEvent{id=3, eventName='Test event3', date=2019-03-07, start=18:00:00, end=20:00:00, eventCreated=2019-03-07 23:28:37.715}
-- event created within 10 sec --
ScheduledEvent{id=3, eventName='Test event3', date=2019-03-07, start=18:00:00, end=20:00:00, eventCreated=2019-03-07 23:28:37.715}

Example Project

Dependencies and Technologies Used:

  • h2 1.4.198: H2 Database Engine.
  • hibernate-core 5.4.1.Final: Hibernate's core ORM functionality.
    Implements javax.persistence:javax.persistence-api version 2.2
  • hibernate-jpamodelgen 5.4.1.Final: Annotation Processor to generate JPA 2 static metamodel classes.
  • JDK 1.8
  • Maven 3.5.4

Examples of Date Time methods in CriteriaBuilder Select All Download
  • jpa-criteria-api-date-time-operations
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • ExampleMain.java
          • resources
            • META-INF

    See Also