Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java criteria builder query not null or empty

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.

like image 208
Crystal Avatar asked Dec 05 '16 16:12

Crystal


2 Answers

Try to use this code:

criteriaBuilder.isNotNull(model.get(entity.name))
like image 199
gfxfunclub Avatar answered Nov 17 '22 11:11

gfxfunclub


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));
like image 42
Tom Taylor Avatar answered Nov 17 '22 09:11

Tom Taylor