8

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:

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

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.

Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
Crystal
  • 28,460
  • 62
  • 219
  • 393

4 Answers4

22

Try to use this code:

criteriaBuilder.isNotNull(model.get(entity.name))
SilverNak
  • 3,283
  • 4
  • 28
  • 44
gfxfunclub
  • 221
  • 2
  • 3
4

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));
Tom Taylor
  • 3,344
  • 2
  • 38
  • 63
0

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.

fabfas
  • 2,200
  • 1
  • 21
  • 21
0

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.

VHS
  • 9,534
  • 3
  • 19
  • 43