How to add or substract a time period to a date in Java Persistence Query Language – JPQL

Octocat **Promotion** - Efficiently manage your coding bookmarks, aka #codingmarks, on and share your hidden gems with the world. They are published weekly on Github. You can help us build THE programming-resources location - Star

There are quite often situations, when you’d need to add or substract a time period to a date when you are accessing the database via Java Persistence API(JPA). Now

  • the bad news is that Java Persistence Query Language(JPQL) does not support such operations on dates yet.
  • the good news is that it is possible by using a native query or doing the computation on the Java side. I prefer the second option as it provides database independence.
  • How To

    Let’s see how it can be done. Consider the following scenario: I need to get recent items(podcasts) from the database, let’s say that were inserted in the last 8 days. For that I’ll build a function that looks back into the past by the numberOfDaysToLookBack parameter:

    public List<Podcast> getRecentPodcasts(int numberOfDaysToLookBack) {
    	Calendar calendar = new GregorianCalendar();
    	calendar.setTimeZone(TimeZone.getTimeZone("UTC+1"));//Munich time
    	calendar.setTime(new Date());
    	calendar.add(Calendar.DATE, -numberOfDaysToLookBack);//substract the number of days to look back
    	Date dateToLookBackAfter = calendar.getTime();
    	String qlString = "SELECT p FROM Podcast p where p.insertionDate > :dateToLookBackAfter";
    	TypedQuery<Podcast> query = entityManager.createQuery(qlString, Podcast.class);		
    	query.setParameter("dateToLookBackAfter", dateToLookBackAfter, TemporalType.DATE);
    	return query.getResultList();

    and call it like getRecentPodcast(8);

    Note that the date calculation takes place in Java. One way to do it is by using the Java Calendar‘s  add function with a negative value.  After that you can use the calculated date as parameter in the JPQL comparison.

    If you don’t like the Java calendar approach, you can achieve the same results with Joda-Time:

    DateTime dateToLookBackAfterJoda = new DateTime(new Date());
    dateToLookBackAfterJoda = dateToLookBackAfterJoda.minusDays(numberOfDaysToLookBack);

    Note: If you want to have an addition instead of substraction use Calendar.add() with a positive value or Joda-Time addDays(int numberOfDays) function.

    Check out also my related posts on the topic

    Podcastpedia image

    Adrian Matei

    Creator of and, computer science engineer, husband, father, curious and passionate about science, computers, software, education, economics, social equity, philosophy - but these are just outside labels and not that important, deep inside we are all just consciousness, right?

    New codingmarks published in week 48 of 2018

    New codingmarks published in week 48 of 2018. Keywords: android, angular, api, documentation, feign, graphql, http, http-client, http2, https, java, kotlin, mapper, mapping, odata, rest, rest-client, spring, spring-boot and swagger Continue reading

    New codingmarks published in week 46 of 2018

    Published on November 20, 2018

    New codingmarks published in week 45of 2018

    Published on November 13, 2018