我正在使用JPA,hibernate 3.
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", traceEntityVO.getLotNumber())
.setParameter("mfrLocId", traceEntityVO.getMfrLocId())
.setParameter("mfrDate", traceEntityVO.getMfrDate())
.setParameter("qtyInitial", traceEntityVO.getQtyInitial())
.setParameter("expDate", traceEntityVO.getExpDate());
当没有空值或空值时,此查询就像一个魅力。但是 traceEntityVO.getLotNumber(),traceEntityVO.getMfrLocId(),traceEntityVO.getExpDate()。
可能有null或空值。在这种情况下,将针对变量检查值“null”或“”,而不是为空条件。当我不确定参数值时,如何处理null或空?
我不想根据值显示动态构造查询,如果为空或空。
这可能吗?
提前致谢..
答案 0 :(得分:2)
答案 1 :(得分:1)
我希望以下代码可以解决您的问题。假设getMfrDate和getExpDate将返回Date Object和其他Number或String对象。但您可以根据返回类型修改IsEmpty。
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 ");
}
答案 2 :(得分:0)
使用条件语句if()根据您的参数(是否为空)构建查询 像这个例子中的日期:
String jpqlQuery = "select f from Formation f where f.libelleFormation Like :libelleFormation and f.statutFormation Like :statutFormation and f.codeFormation Like :codeFormation";
if (critereRecherche.getDateDebFormation() != null) {
jpqlQuery = jpqlQuery.concat(" and f.dateDebFormation > :dateDebFormation");
}
if (critereRecherche.getDateFinFormation() != null) {
jpqlQuery = jpqlQuery.concat(" and f.dateFinFormation < :dateFinFormation");
}
Query query= em.createQuery(jpqlQuery);
query.setParameter("libelleFormation","%"+critereRecherche.getLibelleFormation()+"%");
query.setParameter("statutFormation","%"+critereRecherche.getStatutFormation()+"%");
query.setParameter("codeFormation","%"+critereRecherche.getCodeFormation()+"%");
if (critereRecherche.getDateDebFormation() != null) {
query.setParameter("dateDebFormation",critereRecherche.getDateDebFormation(),TemporalTyp.DATE);
}
if (critereRecherche.getDateFinFormation() != null) {
query.setParameter("dateFinFormation",critereRecherche.getDateFinFormation(),TemporalType.DATE);
}
List<Formation> formations = query.getResultList();
return formations;