Java标准构建器查询不为空或为空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40979316/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java criteria builder query not null or empty
提问by Crystal
I'm trying to check if a column in the db is not an empty string or not null but I can't figure out how to do it with criteria builder queries in order to get actual objects back. This sql works:
我正在尝试检查数据库中的列是否不是空字符串或不为空,但我无法弄清楚如何使用标准构建器查询来获取实际对象。这个 sql 有效:
sampleName is not null and sampleName != ''
But when I try to do it with criteria builder like this:
但是当我尝试使用这样的标准构建器来做到这一点时:
// this is in a private method filterBySampleNotEmpty
// 这是一个私有方法 filterBySampleNotEmpty
cb.notEqual(root.get("sampleName"), "");
called by this in another method
在另一种方法中由此调用
CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
CriteriaQuery<Sample> query = criteriaBuilder.createQuery(Sample.class);
Root model = query.from(Sample.class);
List<Predicate> predicates = new ArrayList<>();
predicates.add(filterBySampleNotEmpty(model, criteriaBuilder));
query.select(model).where(predicates.toArray(new Predicate[]{}));
It returns the whole list still.
它仍然返回整个列表。
采纳答案by Tom Taylor
Please make a try with the following
请尝试以下方法
CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
CriteriaQuery<Sample> query = criteriaBuilder.createQuery(Sample.class);
MetaModel m = em.getMetaModel();
EntityType<Sample> entity = m.entity(Sample.class);
Root model = query.from(Sample.class);
query.where(criteriaBuilder.notEqual(model.get(entity.name), “”)).and(criteriaBuilder.notEqual(model.get(entity.name), null));
回答by fabfas
The criteria builder "notEqual" criteria testing that two expressions are not equal. I can not see the criteria to filter null value unless I missed something.
条件构建器“notEqual”条件测试两个表达式不相等。除非我错过了什么,否则我看不到过滤空值的标准。
回答by VHS
In the 'where' clause, try predicates.toArray(new Predicate[predicates.size()]
and see if that works. When you are converting the List
to Array
, you are specifying the size as 0 since you are passing an empty array.
在“where”子句中,尝试predicates.toArray(new Predicate[predicates.size()]
看看是否有效。当您转换List
to 时Array
,您将大小指定为 0,因为您传递的是一个空数组。
回答by gfxfunclub
Try to use this code:
尝试使用此代码:
criteriaBuilder.isNotNull(model.get(entity.name))