How to handle if query parameter is null or empty in hibernate?

I think you really can't do that without a dynamic query.

Building such a query however is easy with the criteria API (hibernate) (JPA), did you consider it?


I hope following code will sort your problem. Assuming getMfrDate and getExpDate will return Date Object and others either Number or String objects. But you can modify IsEmpty according to return types.

String sqlQuery = " FROM TraceEntityVO  where lotNumber :lotNumber 
and mfrLocId :mfrLocId and mfrDate :mfrDate and qtyInitial :qtyInitial and 
expDate :expDate";

Query query = entityManager.createQuery(sqlQuery)
            .setParameter("lotNumber", isEmpty(traceEntityVO.getLotNumber()))
            .setParameter("mfrLocId", isEmpty(traceEntityVO.getMfrLocId()))
            .setParameter("mfrDate", isEmpty(traceEntityVO.getMfrDate()))
            .setParameter("qtyInitial", isEmpty(traceEntityVO.getQtyInitial()))
            .setParameter("expDate", isEmpty(traceEntityVO.getExpDate()));


private String isEmpty(Object obj) {

    if(obj!=null) {

        if (obj instanceof java.util.Date) {
            return " = to_date('"+obj.toString()+"') ";
        } else if(obj instanceof String) { 
            return " = '"+obj.toString()+"' ";
        } else if (obj instanceof Integer) {
            return " = "+obj.toString()+" ";
          }
    } 

    return new String(" is null ");
 }