Java: JPQL date function to add a time period to another date [closed]

折月煮酒 提交于 2019-11-27 07:37:02

If you have a date object that is + 1 month already you could do something like this:

public List findEmployees(Date endDate) {
  return entityManager.createQuery(
    "SELECT e from Employee e WHERE e.startDate BETWEEN ?1 AND ?2")
    .setParameter(1,new Date(), TemporalType.DATE)
    .setParameter(2,endDate, TemporalType.DATE).getResultList();
}

This however, requires that the dates be valid before hand.

UPDATE

If you always want the next month, you can use JodaTime which has a great and easy api. You could then modify your query like this:

//Get next month
DateTime dt = new DateTime();
entityManager.createQuery(
"SELECT e from Employee e WHERE e.startDate BETWEEN ?1 AND ?2")
.setParameter(1,new Date(), TemporalType.DATE)
.setParameter(2,dt.plusMonths(1).toDate(), TemporalType.DATE).getResultList();

Standard JPQL doesn't support such operations on dates. You will have to either use a native query or to do the computation on the Java side.

Or use commons-lang instead of jodatime:

entityManager.createQuery(
    "SELECT e from Employee e WHERE e.startDate BETWEEN ?1 AND ?2"
)
.setParameter(1,new Date(), TemporalType.DATE)
.setParameter(2,DateUtils.addMonths(new Date(), 1), TemporalType.DATE)
.getResultList();

But I know this is not what you are asking and I'm pretty sure it can't be done in JPQL alone, you will either have to pass a parameter or use a native named query

Dears,

i'm using spring data, the entity save the createdDate as datetime, and in the repository like this:

@Query(value="SELECT t FROM MyEntity t WHERE t.createdDate Between ?1 and ?2")
public List<MyEntity> findAllBetweenDates(Calendar from, Calendar to);

so i can't use :

setParameter(1,new Date(), TemporalType.DATE

in the backend bean i use the following:

    //to set zero of hours,minutes,seconds and milliseconds
    fromCalendar.set(java.util.Calendar.HOUR, 0);
    fromCalendar.set(java.util.Calendar.MINUTE, 0);
    fromCalendar.set(java.util.Calendar.SECOND, 0);
    fromCalendar.set(java.util.Calendar.MILLISECOND, 0);

    toCalendar.set(java.util.Calendar.HOUR, 0);
    toCalendar.set(java.util.Calendar.MINUTE, 0);
    toCalendar.set(java.util.Calendar.SECOND, 0);
    toCalendar.set(java.util.Calendar.MILLISECOND, 0);
    // add 1 days and decrease 1 millisecond
    toCalendar.add(java.util.Calendar.DAY_OF_MONTH, 1);
    toCalendar.add(java.util.Calendar.MILLISECOND, -1);

    allEntities = myEntityRepository.findAllBetweenDates(fromCalendar, toCalendar);
}

and it's working fine.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!