Example usage for javax.persistence.criteria CriteriaBuilder isNull

List of usage examples for javax.persistence.criteria CriteriaBuilder isNull

Introduction

In this page you can find the example usage for javax.persistence.criteria CriteriaBuilder isNull.

Prototype

Predicate isNull(Expression<?> x);

Source Link

Document

Create a predicate to test whether the expression is null.

Usage

From source file:com.ocs.dynamo.dao.query.JpaQueryBuilder.java

/**
 * Creates a JPA2 predicate based on a Filter
 * /*from   ww  w.jav a2  s . c o  m*/
 * @param filter
 *            the filter
 * @param builder
 *            the criteria builder
 * @param root
 *            the entity root
 * @return
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
private static Predicate createPredicate(Filter filter, CriteriaBuilder builder, Root<?> root) {
    if (filter == null) {
        return null;
    }

    if (filter instanceof And) {
        return createAndPredicate(builder, root, filter);
    } else if (filter instanceof Or) {
        return createOrPredicate(builder, root, filter);
    } else if (filter instanceof Not) {
        Not not = (Not) filter;
        return builder.not(createPredicate(not.getFilter(), builder, root));
    } else if (filter instanceof Between) {
        Between between = (Between) filter;
        Expression property = getPropertyPath(root, between.getPropertyId());
        return builder.between(property, (Comparable) between.getStartValue(),
                (Comparable) between.getEndValue());
    } else if (filter instanceof Compare) {
        return createComparePredicate(builder, root, filter);
    } else if (filter instanceof IsNull) {
        IsNull isNull = (IsNull) filter;
        return builder.isNull(getPropertyPath(root, isNull.getPropertyId()));
    } else if (filter instanceof Like) {
        return createLikePredicate(builder, root, filter);
    } else if (filter instanceof Contains) {
        Contains contains = (Contains) filter;
        return builder.isMember(contains.getValue(),
                (Expression) getPropertyPath(root, contains.getPropertyId()));
    } else if (filter instanceof In) {
        In in = (In) filter;
        if (in.getValues() != null && !in.getValues().isEmpty()) {
            Expression exp = getPropertyPath(root, in.getPropertyId());
            return exp.in(in.getValues());
        } else {
            Expression exp = getPropertyPath(root, in.getPropertyId());
            return exp.in(Lists.newArrayList(-1));
        }
    } else if (filter instanceof Modulo) {
        return createModuloPredicate(builder, root, filter);
    }

    throw new UnsupportedOperationException("Filter: " + filter.getClass().getName() + " not recognized");
}

From source file:core.commonapp.server.dao.party.PersonDaoHibernateImpl.java

@Override
@Transactional//from  ww w  .  jav a  2  s.  c  o  m
public List<Person> findAllContactPeople(Integer partyId) {
    CriteriaBuilder builder = getEntityManager().getCriteriaBuilder();
    CriteriaQuery<Person> query = builder.createQuery(Person.class);

    Root<Person> contactPerson = query.from(Person.class);
    Join<Person, PartyRelationship> partyToRelationships = contactPerson.join("partyToRelationships");

    query.where(builder.equal(partyToRelationships.get("partyFrom.partyId"), partyId),
            builder.isNull(partyToRelationships.get("thruDate")));

    List<Person> people = getEntityManager().createQuery(query).getResultList();

    PartyDaoHibernateImpl.lazyLoad((Party) people, true, true, false, false);

    return people;
}

From source file:com.jaxio.jpa.querybyexample.ByPropertySelectorUtil.java

private <E> void byObjectOrModeSelector(Root<E> root, CriteriaBuilder builder, List<Predicate> predicates,
        SearchParameters sp, PropertySelector<? super E, ?> selector) {
    List<Predicate> selectorPredicates = newArrayList();
    Path<?> path = jpaUtil.getPath(root, selector.getAttributes());
    List<?> selected = selector.getSelected();
    if (selected.contains(null)) {
        selected = newArrayList(selector.getSelected());
        selected.remove(null);/*from   ww  w.ja  va 2 s  .  c  om*/
        selectorPredicates.add(builder.isNull(path));
    }
    if (isNotEmpty(selected)) {
        if (selected.get(0) instanceof Identifiable) {
            List<Serializable> ids = newArrayList();
            for (Object selection : selected) {
                ids.add(((Identifiable<?>) selection).getId());
            }
            selectorPredicates.add(path.get("id").in(ids));
        } else {
            selectorPredicates.add(path.in(selected));
        }
    }
    predicates.add(jpaUtil.orPredicate(builder, selectorPredicates));
}

From source file:com.dbs.sdwt.jpa.ByPropertySelectorUtil.java

private <E> void byBooleanSelector(Root<E> root, CriteriaBuilder builder, List<Predicate> predicates,
        SearchParameters sp, PropertySelector<? super E, Boolean> selector) {
    if (selector.isNotEmpty()) {
        List<Predicate> selectorPredicates = newArrayList();

        for (Boolean selection : selector.getSelected()) {
            Path<Boolean> path = jpaUtil.getPath(root, selector.getAttributes());
            if (selection == null) {
                selectorPredicates.add(builder.isNull(path));
            } else {
                selectorPredicates.add(selection ? builder.isTrue(path) : builder.isFalse(path));
            }//from ww  w . ja  v  a  2  s .  com
        }
        if (selector.isOrMode()) {
            predicates.add(jpaUtil.orPredicate(builder, selectorPredicates));
        } else {
            predicates.add(jpaUtil.andPredicate(builder, selectorPredicates));
        }
    }
}

From source file:com.dbs.sdwt.jpa.ByPropertySelectorUtil.java

private <E> void byObjectOrModeSelector(Root<E> root, CriteriaBuilder builder, List<Predicate> predicates,
        SearchParameters sp, PropertySelector<? super E, ?> selector) {
    List<Predicate> selectorPredicates = newArrayList();
    Path<?> path = jpaUtil.getPath(root, selector.getAttributes());
    List<?> selected = selector.getSelected();
    if (selected.contains(null)) {
        selected = newArrayList(selector.getSelected());
        selected.remove(null);//  ww  w.  ja v  a2 s  . co m
        selectorPredicates.add(builder.isNull(path));
    }
    if (isNotEmpty(selected)) {
        if (selected.get(0) instanceof Identifiable) {
            List<Serializable> ids = newArrayList();
            for (Object selection : selected) {
                ids.add(((Identifiable<?>) selection).getId());
            }
            if (SearchMode.NOT_IN == selector.getSearchMode()) {
                selectorPredicates.add(builder.not(path.get("id").in(ids)));
            } else {
                selectorPredicates.add(path.get("id").in(ids));
            }
        } else {
            if (SearchMode.NOT_IN == selector.getSearchMode()) {
                selectorPredicates.add(builder.not(path.in(selected)));
            } else {
                selectorPredicates.add(path.in(selected));
            }

        }
    }

    predicates.add(jpaUtil.orPredicate(builder, selectorPredicates));
}

From source file:com.expressui.sample.view.role.RoleQuery.java

@Override
public List<Predicate> buildCriteria(CriteriaBuilder builder, Root<Role> rootEntity) {
    List<Predicate> criteria = new ArrayList<Predicate>();

    if (!isEmpty(name)) {
        ParameterExpression<String> p = builder.parameter(String.class, "name");
        criteria.add(builder.like(builder.upper(rootEntity.<String>get("name")), p));
    }/*from  www. ja  va 2s  .c  om*/

    if (!isEmpty(doesNotBelongToUser)) {
        ParameterExpression<User> p = builder.parameter(User.class, "doesNotBelongToUser");
        Join join = rootEntity.join("userRoles", JoinType.LEFT);
        criteria.add(builder.or(builder.notEqual(join.get("user"), p), builder.isNull(join.get("user"))));
    }

    return criteria;
}

From source file:com.expressui.sample.view.user.UserQuery.java

@Override
public List<Predicate> buildCriteria(CriteriaBuilder builder, Root<User> rootEntity) {
    List<Predicate> criteria = new ArrayList<Predicate>();

    if (!isEmpty(loginName)) {
        ParameterExpression<String> p = builder.parameter(String.class, "loginName");
        criteria.add(builder.like(builder.upper(rootEntity.<String>get("loginName")), p));
    }//from ww w.ja  v a  2  s  . c  om

    if (!isEmpty(doesNotBelongToRole)) {
        ParameterExpression<Role> p = builder.parameter(Role.class, "doesNotBelongToRole");
        Join join = rootEntity.join("userRoles", JoinType.LEFT);
        criteria.add(builder.or(builder.notEqual(join.get("role"), p), builder.isNull(join.get("role"))));
    }

    return criteria;
}

From source file:com.bxf.hradmin.common.utils.QueryParameterTransformer.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public static Predicate generatePredicate(Root root, CriteriaBuilder builder,
        QueryParameter... queryParameters) {
    Predicate condition = builder.conjunction();
    for (QueryParameter queryParameter : queryParameters) {
        Object value = queryParameter.getValue();
        if (value == null || StringUtils.isBlank(value.toString())) {
            continue;
        }/* w ww . j ava 2 s .c  o  m*/
        Path path = root.get(queryParameter.getKey());
        switch (queryParameter.getMode()) {
        case BETWEEN:
            Object[] values = asArray(value);
            if (values != null) {
                condition = builder.and(builder.between((Path<Comparable>) path, asComparable(values[0]),
                        asComparable(values[1])));
            }
            break;
        case GREATER_THAN:
            condition = builder.and(condition,
                    builder.greaterThan((Path<Comparable>) path, asComparable(value)));
            break;
        case GREATER_EQUALS:
            condition = builder.and(condition,
                    builder.greaterThanOrEqualTo((Path<Comparable>) path, asComparable(value)));
            break;
        case LESS_THAN:
            condition = builder.and(condition, builder.lessThan((Path<Comparable>) path, asComparable(value)));
            break;
        case LESS_EQUALS:
            condition = builder.and(condition,
                    builder.lessThanOrEqualTo((Path<Comparable>) path, asComparable(value)));
            break;
        case IS_NULL:
            condition = builder.and(condition, builder.isNull(path));
            break;
        case IS_NOT_NULL:
            condition = builder.and(condition, builder.isNotNull(path));
            break;
        case IN:
            condition = builder.and(condition, path.in(asArray(value)));
            break;
        case NOT_IN:
            condition = builder.and(condition, builder.not(path.in(asArray(value))));
            break;
        case LIKE:
            condition = builder.and(condition, builder.like(path, "%" + String.valueOf(value) + "%"));
            break;
        case NOT_LIKE:
            condition = builder.and(condition, builder.notLike(path, "%" + String.valueOf(value) + "%"));
            break;
        case EQUALS:
            condition = builder.and(condition, builder.equal(path, value));
            break;
        case NOT_EQUALS:
            condition = builder.and(condition, builder.notEqual(path, value));
            break;
        default:
            break;
        }
    }
    return condition;
}

From source file:com.qpark.eip.core.spring.statistics.dao.StatisticsLoggingDao.java

/**
 * Add the {@link SystemUserLogType} to the database.
 *
 * @param log//w w w  . j  a va 2 s  . c  o  m
 *            the {@link SystemUserLogType} to add.
 */
private void addChannelInvocation(final SystemUserLogType log) {
    /* Setup context and version. */
    log.setContext(this.getContextName());
    log.setVersion(this.getContextVersion());
    if (log.getUserName() != null && log.getUserName().trim().length() == 0) {
        log.setUserName(null);
    }

    /* Setup to search existing one. */
    final CriteriaBuilder cb = this.em.getCriteriaBuilder();
    final CriteriaQuery<SystemUserLogType> q = cb.createQuery(SystemUserLogType.class);
    final Root<SystemUserLogType> c = q.from(SystemUserLogType.class);

    final List<Predicate> predicates = new ArrayList<Predicate>();
    predicates.add(cb.equal(c.<String>get(SystemUserLogType_.context), log.getContext()));
    predicates.add(cb.equal(c.<String>get(SystemUserLogType_.version), log.getVersion()));
    if (log.getUserName() == null) {
        predicates.add(cb.isNull(c.<String>get(SystemUserLogType_.userName)));
    } else {
        predicates.add(cb.equal(c.<String>get(SystemUserLogType_.userName), log.getUserName()));
    }
    predicates.add(cb.equal(c.<String>get(SystemUserLogType_.serviceName), log.getServiceName()));
    predicates.add(cb.equal(c.<String>get(SystemUserLogType_.operationName), log.getOperationName()));
    predicates.add(cb.between(c.<Date>get(SystemUserLogType_.logDateItem), getDayStart(log.getLogDateItem()),
            getDayEnd(log.getLogDateItem())));

    q.where(predicates.toArray(new Predicate[predicates.size()]));
    q.orderBy(cb.desc(c.<Long>get(SystemUserLogType_.hjid)));
    TypedQuery<SystemUserLogType> typedQuery = this.em.createQuery(q);

    SystemUserLogType persistence = null;
    synchronized (StatisticsLoggingDao.class) {
        try {
            persistence = typedQuery.getSingleResult();
            if (persistence == null) {
                /* Not found -> persist */
                persistence = log;
                this.setupSystemUserLog(persistence, null);
                this.em.persist(persistence);
            } else {
                /* Found -> add and merge */
                this.setupSystemUserLog(persistence, log);
                this.em.merge(persistence);
            }
        } catch (final NoResultException e) {
            /* Not found -> persist */
            persistence = log;
            this.setupSystemUserLog(persistence, null);
            this.em.persist(persistence);
        } catch (final NonUniqueResultException e) {
            /* Found more */
            typedQuery = this.em.createQuery(q);
            final List<SystemUserLogType> list = typedQuery.getResultList();
            SystemUserLogType l;
            for (int i = 0; i < list.size(); i++) {
                l = list.get(i);
                if (persistence == null && l.getHjid() != null) {
                    persistence = l;
                    break;
                }
            }
            if (persistence != null) {
                /* Found more -> condense to first valid one -> merge. */
                this.setupSystemUserLog(persistence, log);
                for (int i = list.size() - 1; i >= 0; i--) {
                    l = list.get(i);
                    if (l != null && l.getHjid() != null) {
                        if (persistence.getHjid().equals(l.getHjid())) {
                        } else {
                            this.setupSystemUserLog(persistence, l);
                            list.remove(i);
                            this.em.remove(l);
                        }
                    }
                }
                this.em.merge(persistence);
            } else {
                /* Found more -> no valid one in list -> persist. */
                persistence = log;
                this.setupSystemUserLog(persistence, null);
                this.em.persist(persistence);
            }
        }
    }
    this.logger.debug("addChannelInvocation SystemUserLog {} {} {} {} {} {}",
            this.contextNameProvider.getContextName(), this.contextNameProvider.getContextVersion(),
            String.valueOf(persistence.getUserName()), persistence.getServiceName(),
            persistence.getOperationName(), persistence.getLogDate().toXMLFormat());
}

From source file:org.oncoblocks.centromere.jpa.QueryCriteriaSpecification.java

public Predicate toPredicate(Root<T> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
    String key = queryCriteria.getKey();
    Object value = queryCriteria.getValue();
    Evaluation eval = queryCriteria.getEvaluation();
    Path path = null;//from w w  w  .j  a  v  a 2  s. co m
    if (key.contains(".")) {
        String[] bits = key.split("\\.");
        path = root.join(bits[0]).get(bits[1]);
    } else {
        path = root.get(key);
    }
    logger.debug(String.format("[CENTROMERE] Converting QueryCriteria to JPA specification: %s",
            queryCriteria.toString()));
    switch (eval) {
    case EQUALS:
        return criteriaBuilder.equal(path, value);
    case NOT_EQUALS:
        return criteriaBuilder.notEqual(path, value);
    case IN:
        return path.in(value);
    case NOT_IN:
        return criteriaBuilder.not(path.in(value));
    case IS_NULL:
        return criteriaBuilder.isNull(path);
    case NOT_NULL:
        return criteriaBuilder.isNotNull(path);
    case GREATER_THAN:
        return criteriaBuilder.greaterThan(path, value.toString());
    case GREATER_THAN_EQUALS:
        return criteriaBuilder.greaterThanOrEqualTo(path, value.toString());
    case LESS_THAN:
        return criteriaBuilder.lessThan(path, value.toString());
    case LESS_THAN_EQUALS:
        return criteriaBuilder.lessThanOrEqualTo(path, value.toString());
    case BETWEEN:
        return criteriaBuilder.and(criteriaBuilder.greaterThan(path, ((List<?>) value).get(0).toString()),
                criteriaBuilder.lessThan(path, ((List<?>) value).get(1).toString()));
    case OUTSIDE:
        return criteriaBuilder.or(criteriaBuilder.greaterThan(path, ((List<?>) value).get(1).toString()),
                criteriaBuilder.lessThan(path, ((List<?>) value).get(0).toString()));
    case BETWEEN_INCLUSIVE:
        return criteriaBuilder.and(
                criteriaBuilder.greaterThanOrEqualTo(path, ((List<?>) value).get(0).toString()),
                criteriaBuilder.lessThanOrEqualTo(path, ((List<?>) value).get(1).toString()));
    case OUTSIDE_INCLUSIVE:
        return criteriaBuilder.or(
                criteriaBuilder.greaterThanOrEqualTo(path, ((List<?>) value).get(1).toString()),
                criteriaBuilder.lessThanOrEqualTo(path, ((List<?>) value).get(0).toString()));
    case LIKE:
        return criteriaBuilder.like(path, "%" + value.toString() + "%");
    case NOT_LIKE:
        return criteriaBuilder.notLike(path, "%" + value.toString() + "%");
    case STARTS_WITH:
        return criteriaBuilder.like(path, value.toString() + "%");
    case ENDS_WITH:
        return criteriaBuilder.like(path, "%" + value.toString());
    default:
        return criteriaBuilder.equal(root.get(queryCriteria.getKey()), queryCriteria.getValue());
    }
}