1

I have the following HQL and I would like to know how it handles comparing date column to null. For example what happens in case the givenTime parameter is null. I checked and got empty results. Is it always the case? is it documented?

select mo from MyClassMO mo
where mo.creationDate is not null and mo.creationDate >= (:givenTime)

and what if the givenTime replaced with inner select query which returns null? thanks

alexbt
  • 16,415
  • 6
  • 78
  • 87
user1116377
  • 629
  • 3
  • 15
  • 31

2 Answers2

0

I know you asked about hql but for handling such a cases I prefer using something called Criteria in hibernate. It can be mixed up easy with SQL.

JPA and Hibernate - Criteria vs. JPQL or HQL

Criteria criteria = session
            .createCriteria(MyClassMO.class)
               .add(Restrictions.isNotNull("creationDate"));
if (givenTime!=null){
    criteria.add(Restrictions.ge("creationDate", givenTime));//ge - greater equals
}
List<MyClassMO> result = criteria.list();
Community
  • 1
  • 1
daredesm
  • 597
  • 2
  • 7
  • 22
-1

If your parameter is nullable, you must manage it manually.

In base of your applied logic, you can write the query.

I suppose some cases (tell me if your is one of these or another).

Case 1: Not consider givenTime in filter

You can wirte this query:

String hql = "select mo from MyClassMO mo" + 
     " where mo.creationDate is not null";

if (givenTime != null) {
    hql += " and mo.creationDate >= (:givenTime)";
}

Case 2: if givenTime is null, put the current date

String hql = "select mo from MyClassMO mo" + 
    " where mo.creationDate is not null " +
    " and mo.creationDate >= COALESCE(:givenTime, current_date())";

Case 3: if givenTime is in subquery returns null, put the current date

String hql = "select mo from MyClassMO mo" + 
    " where mo.creationDate is not null " +
    " and mo.creationDate >= "
    " (SELECT COALESCE(:giventime, current_date()) " +
    "  FROM yourtable WHERE conditions";
Joe Taras
  • 15,166
  • 7
  • 42
  • 55