如果查询参数在Hibernate中为空或空的时候如何处理? [英] How to handle if query parameter is null or empty in hibernate?
问题描述
字符串sqlQuery =FROM TraceEntityVO其中lotNumber =:lotNumber和mfrLocId = :mfrLocId和mfrDate =:mfrDate和qtyInitial =:qtyInitial和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或空值,我该如何处理?
我不想构造查询如果为空或空值,则动态根据这些值动态地进行分析。
这可能吗?
在此先感谢..
我认为如果没有动态查询,您真的无法做到这一点。
然而,使用标准API构建这样的查询很容易( hibernate )( JPA ),你认为它吗?
I'm using 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());
This query works like a charm when the there were no empty or null values. But there could be possible of null or empty value for traceEntityVO.getLotNumber(),traceEntityVO.getMfrLocId(),traceEntityVO.getExpDate().
In this case the value 'null' or '' is checked against the variable instead of is null condition. How do I handle when I'm not sure about the parameter value, either null or empty?
I don't want to construct the query dynamically based on the values if empty or null.
Is this possible?
Thanks in advance..
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?
这篇关于如果查询参数在Hibernate中为空或空的时候如何处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!