Example usage for org.hibernate.criterion Restrictions isNotNull

List of usage examples for org.hibernate.criterion Restrictions isNotNull

Introduction

In this page you can find the example usage for org.hibernate.criterion Restrictions isNotNull.

Prototype

public static Criterion isNotNull(String propertyName) 

Source Link

Document

Apply an "is not null" constraint to the named property

Usage

From source file:com.jubination.model.dao.ClientDAOImpl.java

@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
public List fetchEntities(String paramVal) {
    List list = null;//w w  w .ja  v a2 s.  c  o m

    switch (paramVal) {

    case "PendingMinusOne":
        session = getSessionFactory().getCurrentSession();
        Criteria criteria = session.createCriteria(Client.class, "c");
        criteria.createAlias("c.lead", "l");
        criteria.add(Restrictions.and(Restrictions.lt("l.count", 0), Restrictions.isNull("l.followUpDate"),
                Restrictions.gt("l.leadId", "50000")));
        criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
        list = criteria.list();

        for (Client client : (List<Client>) list) {
            client.getLead().size();
            for (Lead lead : client.getLead()) {
                if (lead.getBeneficiaries() != null) {
                    lead.getBeneficiaries().size();
                }
                lead.getCall().size();
            }
        }
        break;
    case "PendingInProgress":
        session = getSessionFactory().getCurrentSession();
        criteria = session.createCriteria(Client.class, "c");
        criteria.createAlias("c.lead", "l");
        criteria.createAlias("l.call", "call");
        criteria.add(Restrictions.and(Restrictions.le("l.count", 0), Restrictions.gt("l.leadId", "50000"),
                Restrictions.eq("call.Status", "in-progress")));
        criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
        list = criteria.list();

        for (Client client : (List<Client>) list) {
            client.getLead().size();
            for (Lead lead : client.getLead()) {
                if (lead.getBeneficiaries() != null) {
                    lead.getBeneficiaries().size();
                }
                lead.getCall().size();
            }
        }
        break;
    case "PendingAndNotified":
        session = getSessionFactory().getCurrentSession();
        criteria = session.createCriteria(Client.class, "c");
        criteria.createAlias("c.lead", "l");
        criteria.add(Restrictions.or(Restrictions.and(

                Restrictions.ge("l.count", 1), Restrictions.eq("l.followUpDate", ""),
                Restrictions.isNull("l.followUpDate")),

                Restrictions.and(Restrictions.ge("l.count", 1), Restrictions.ne("l.followUpDate", ""),
                        Restrictions.isNotNull("l.followUpDate"),
                        Restrictions.le("l.followUpDate",
                                new SimpleDateFormat("yyyy-MM-dd").format(new Date()))),
                Restrictions.eq("l.followUpDate", new SimpleDateFormat("yyyy-MM-dd").format(new Date())))

        );
        criteria.addOrder(Order.desc("l.followUpDate"));
        criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
        list = criteria.list();

        for (Client client : (List<Client>) list) {
            client.getLead().size();
            for (Lead lead : client.getLead()) {
                if (lead.getBeneficiaries() != null) {
                    lead.getBeneficiaries().size();
                }
                lead.getCall().size();
            }
        }
        break;

    case "Pending":
        session = getSessionFactory().getCurrentSession();
        criteria = session.createCriteria(Client.class, "c");
        criteria.createAlias("c.lead", "l");
        criteria.add(Restrictions.and(Restrictions.and(Restrictions.ge("l.count", 1),
                Restrictions.isNull("l.missedAppointment"), Restrictions.isNull("l.followUpDate"))));

        criteria.addOrder(Order.asc("l.count"));
        criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
        list = criteria.list();
        for (Client client : (List<Client>) list) {
            client.getLead().size();
            for (Lead lead : client.getLead()) {
                if (lead.getBeneficiaries() != null) {
                    lead.getBeneficiaries().size();
                }
                lead.getCall().size();

            }
        }
        break;
    case "Notified":
        session = getSessionFactory().getCurrentSession();
        criteria = session.createCriteria(Client.class, "c");
        criteria.createAlias("c.lead", "l");
        criteria.add(
                Restrictions.or(
                        Restrictions.and(
                                Restrictions
                                        .and(Restrictions.ge("l.count", 1),
                                                Restrictions.and(
                                                        Restrictions.le("l.followUpDate",
                                                                new SimpleDateFormat("yyyy-MM-dd")
                                                                        .format(new Date())),
                                                        Restrictions.gt("l.followUpDate", "2016-01-01"))),
                                Restrictions.isNull("l.missedAppointment")),
                        Restrictions.and(
                                Restrictions.eq("l.followUpDate",
                                        new SimpleDateFormat("yyyy-MM-dd").format(new Date())),
                                Restrictions.eq("l.leadStatus", "Follow up/Call back"))));
        criteria.addOrder(Order.asc("l.followUpDate"));
        criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
        list = criteria.list();
        for (Client client : (List<Client>) list) {
            client.getLead().size();
            for (Lead lead : client.getLead()) {
                if (lead.getBeneficiaries() != null) {
                    lead.getBeneficiaries().size();
                }
                lead.getCall().size();
            }
        }
        break;
    case "PendingMA":
        session = getSessionFactory().getCurrentSession();
        criteria = session.createCriteria(Client.class, "c");
        criteria.createAlias("c.lead", "l");
        criteria.add(Restrictions.and(Restrictions.ge("l.count", 1),
                Restrictions.eq("l.missedAppointment", true), Restrictions.isNull("l.followUpDate")));

        criteria.addOrder(Order.desc("l.count"));
        criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
        list = criteria.list();
        for (Client client : (List<Client>) list) {
            client.getLead().size();
            for (Lead lead : client.getLead()) {
                if (lead.getBeneficiaries() != null) {
                    lead.getBeneficiaries().size();
                }
                lead.getCall().size();
            }
        }
        break;
    case "NotifiedMA":
        session = getSessionFactory().getCurrentSession();
        criteria = session.createCriteria(Client.class);
        criteria.createAlias("lead", "l");
        criteria.add(Restrictions.and(
                Restrictions.and(Restrictions.ge("l.count", 1),
                        Restrictions.and(
                                Restrictions.le("l.followUpDate",
                                        new SimpleDateFormat("yyyy-MM-dd").format(new Date())),
                                Restrictions.gt("l.followUpDate", "2016-01-01"))),
                Restrictions.eq("l.missedAppointment", true)));
        criteria.addOrder(Order.asc("l.followUpDate"));
        criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
        list = criteria.list();
        for (Client client : (List<Client>) list) {
            client.getLead().size();
            for (Lead lead : client.getLead()) {
                if (lead.getBeneficiaries() != null) {
                    lead.getBeneficiaries().size();
                }
                lead.getCall().size();
            }
        }
        break;

    case "Overnight":
        session = getSessionFactory().getCurrentSession();
        criteria = session.createCriteria(Client.class);
        criteria.add(Restrictions.eq("overnight", true));
        list = criteria.list();
        for (Client client : (List<Client>) list) {
            for (Lead lead : client.getLead()) {
                if (lead.getBeneficiaries() != null) {
                    lead.getBeneficiaries().size();
                }
                lead.getCall().size();
            }
            client.getLead().size();
        }
        break;

    default:

        break;
    }
    if (list != null) {
        System.out.println("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$" + list.size() + "$$$" + paramVal);
    }

    System.out.println(
            "READ CLIENT WITH INNER ELEMENTS WITH STATUS :::::::::::::::::::::::::::::::::::::::::::::::CHECK");
    return list;

}

From source file:com.klistret.cmdb.utility.hibernate.XPathCriteria.java

License:Open Source License

/**
 * //  w w  w.j av  a  2s . co  m
 * @param predicate
 * @return
 */
protected Criterion getRestriction(Expr predicate, HibernateStep context) {
    logger.debug("Adding restrictions by predicate to context [{}]", context);

    switch (predicate.getType()) {
    case Or:
        /**
         * Recursively breaks down the OrExpr by translating on the first
         * and second operands
         */
        if (((OrExpr) predicate).getOperands().size() != 2)
            throw new ApplicationException(
                    String.format("OrExpr expression [%s] expects 2 operands", predicate));

        return Restrictions.or(getRestriction(((OrExpr) predicate).getOperands().get(0), context),
                getRestriction(((OrExpr) predicate).getOperands().get(1), context));
    case And:
        /**
         * Recursively breaks down the AndExpr by translating on the first
         * and second operands
         */
        if (((AndExpr) predicate).getOperands().size() != 2)
            throw new ApplicationException(
                    String.format("AndExpr expression [%s] expects 2 operands", predicate));

        return Restrictions.and(getRestriction(((AndExpr) predicate).getOperands().get(0), context),
                getRestriction(((AndExpr) predicate).getOperands().get(1), context));
    case Comparison:
        /**
         * Find the literal
         */
        LiteralExpr literal = getLiteralOperand(((ComparisonExpr) predicate).getOperands());

        /**
         * Find the relative path making a Hibernate relative path
         */
        RelativePathExpr rpe = getRelativePathOperand(((ComparisonExpr) predicate).getOperands());
        HibernateRelativePath hRPath = process(rpe, context);
        build(hRPath);

        HibernateStep last = hRPath.getLastHibernateStep();

        /**
         * Property name with alias prefix
         */
        String alias = last.getPrevious() == null ? aliasCache.get(context.getPath())
                : aliasCache.get(last.getPrevious().getPath());
        String propertyName = alias == null ? last.getName() : String.format("%s.%s", alias, last.getName());

        /**
         * Paths with XML properties (always the last step if present)
         * return a XPath restriction.
         */
        if (hRPath.hasXML()) {
            if (!hRPath.isTruncated())
                throw new ApplicationException(String.format(
                        "Predicate relative path ending in an XML property [%s] must be truncated", last));

            /**
             * Last Hibernate step of the Hibernate path marks the property
             * which the restriction acts on.
             */
            StepExpr step = (StepExpr) last.getStep();

            /**
             * A new XPath is created from the last step downwards till the
             * step prior to the ending step.
             */
            String xpath = null;
            for (int depth = step.getDepth(); depth < step.getRelativePath().getDepth() - 1; depth++) {
                Expr expr = step.getRelativePath().getExpr(depth);
                xpath = xpath == null ? expr.getXPath() : String.format("%s/%s", xpath, expr.getXPath());
            }

            Step ending = (Step) step.getRelativePath().getLastExpr();

            /**
             * A new comparison is generated
             */
            List<Expr> operands = new ArrayList<Expr>();
            operands.add(ending);
            operands.add(literal);

            xpath = String.format("%s[%s]", xpath,
                    ComparisonExpr.getXPath(((ComparisonExpr) predicate).getOperator(), operands, false));
            xpath = String.format("%s%s", context.getBaseExpression().getProlog(), xpath);

            PathExpression other = new PathExpression(xpath);
            return new XPathRestriction(propertyName, (Step) other.getRelativePath().getFirstExpr());
        }

        if (((StepExpr) last.getStep()).hasPredicates())
            throw new ApplicationException(String.format(
                    "Comparisons against Hibernate properties may not have an underlying step [] with predicates",
                    last.getStep()));

        logger.debug("Predicate is comparison [{}] against property [{}]",
                ((ComparisonExpr) predicate).getOperator().name(), propertyName);

        switch (((ComparisonExpr) predicate).getOperator()) {
        case ValueEquals:
            logger.debug("Value: {}", literal.getValue().getJavaValue());
            return Restrictions.eq(propertyName, literal.getValue().getJavaValue());
        case ValueGreaterThan:
            logger.debug("Value: {}", literal.getValue().getJavaValue());
            return Restrictions.gt(propertyName, literal.getValue().getJavaValue());
        case ValueGreaterThanOrEquals:
            logger.debug("Value: {}", literal.getValue().getJavaValue());
            return Restrictions.ge(propertyName, literal.getValue().getJavaValue());
        case ValueLessThan:
            logger.debug("Value: {}", literal.getValue().getJavaValue());
            return Restrictions.lt(propertyName, literal.getValue().getJavaValue());
        case ValueLessThanOrEquals:
            logger.debug("Value: {}", literal.getValue().getJavaValue());
            return Restrictions.le(propertyName, literal.getValue().getJavaValue());
        case ValueNotEquals:
            logger.debug("Value: {}", literal.getValue().getJavaValue());
            return Restrictions.ne(propertyName, literal.getValue().getJavaValue());
        case GeneralEquals:
            /**
             * If atomic (not a sequence) then the 'in' restriction is not
             * usable (defaults to 'eq' restriction) since the argument is
             * an array of objects.
             */
            if (literal.isAtomic()) {
                logger.debug("Value: {}", literal.getValue().getJavaValue());
                return Restrictions.eq(propertyName, literal.getValue().getJavaValue());
            }

            logger.debug("Values: {}", literal.getValues());

            Object[] javaValues = new Object[literal.getValues().length];
            for (int index = 0; index < literal.getValues().length; index++)
                javaValues[index] = ((com.klistret.cmdb.utility.saxon.Value) literal.getValues()[index])
                        .getJavaValue();

            return Restrictions.in(propertyName, javaValues);
        case Matches:
            if (((ComparisonExpr) predicate).getOperands().size() != 2)
                throw new ApplicationException(
                        String.format("Matches function [%s] expects 2 operands", predicate));

            logger.debug("Value: {}", literal.getValue().getText());
            return Restrictions.ilike(propertyName, literal.getValue().getText(), MatchMode.EXACT);
        case Exists:
            if (((ComparisonExpr) predicate).getOperands().size() != 1)
                throw new ApplicationException(
                        String.format("Exists function [%s] expects only 1 operand", predicate));

            return Restrictions.isNotNull(propertyName);
        case Empty:
            if (((ComparisonExpr) predicate).getOperands().size() != 1)
                throw new ApplicationException(
                        String.format("Empty function [%s] expects only 1 operand", predicate));

            return Restrictions.isNull(propertyName);
        default:
            throw new ApplicationException(
                    String.format("Unexpected comparison operator [%s] handling predicates",
                            ((ComparisonExpr) predicate).getOperator()));
        }

    default:
        throw new ApplicationException(String.format("Unexpected expr [%s] type for predicate", predicate));
    }
}

From source file:com.kodemore.hibernate.criteria.KmAbstractCriteria.java

License:Open Source License

public void addIsNotNull(String property) {
    _add(Restrictions.isNotNull(property));
}

From source file:com.krawler.common.util.BuildCriteria.java

License:Open Source License

private static Criterion getCriteriaByCondition(Object value, Integer criteriaVal, String propertyname) {
    Criterion Criteriaobj;//from w  w w.j a va  2 s  .c o m

    switch (criteriaVal) {
    case ISNOTNULL:
        Criteriaobj = Restrictions.isNotNull(propertyname);
        break;
    case NOTIN:
        String[] strArr = String.valueOf(value).split(",");
        List ls = Arrays.asList(strArr);
        Criteriaobj = Restrictions.not(Restrictions.in(propertyname, ls));
        break;
    case LIKE:
        Criteriaobj = Restrictions.or(Restrictions.like(propertyname, value + "%"),
                Restrictions.like(propertyname, "% " + value + "%"));
        break;
    case LE:
        Criteriaobj = Restrictions.le(propertyname, value);
        break;
    case GE:
        Criteriaobj = Restrictions.ge(propertyname, value);
        break;
    case ISNULL:
        Criteriaobj = Restrictions.isNull(propertyname);
        break;
    case IN:
        strArr = String.valueOf(value).split(",");
        ls = Arrays.asList(strArr);
        Criteriaobj = Restrictions.in(propertyname, ls);
        break;
    case NE:
        Criteriaobj = Restrictions.ne(propertyname, value);
        break;
    case LT:
        Criteriaobj = Restrictions.lt(propertyname, value);
        break;
    case GT:
        Criteriaobj = Restrictions.gt(propertyname, value);
        break;
    case EQ:
    default:
        Criteriaobj = Restrictions.eq(propertyname, value);
        break;
    }
    return Criteriaobj;
}

From source file:com.liferay.portal.workflow.jbpm.dao.CustomSession.java

License:Open Source License

public int countProcessInstances(long processDefinitionId, Boolean completed) {

    try {/*  w w  w . j a va 2s .com*/
        Criteria criteria = _session.createCriteria(ProcessInstance.class);

        criteria.setProjection(Projections.countDistinct("id"));

        criteria.add(Restrictions.eq("processDefinition.id", processDefinitionId));

        if (completed != null) {
            if (completed.booleanValue()) {
                criteria.add(Restrictions.isNotNull("end"));
            } else {
                criteria.add(Restrictions.isNull("end"));
            }
        }

        Number count = (Number) criteria.uniqueResult();

        return count.intValue();
    } catch (Exception e) {
        throw new JbpmException(e);
    }
}

From source file:com.liferay.portal.workflow.jbpm.dao.CustomSession.java

License:Open Source License

public int countTaskInstances(long processInstanceId, long tokenId, String[] actorIds, boolean pooledActors,
        Boolean completed) {// w  ww .  jav a  2s  . c o m

    if ((actorIds != null) && (actorIds.length == 0)) {
        return 0;
    }

    try {
        Criteria criteria = _session.createCriteria(TaskInstance.class);

        criteria.setProjection(Projections.countDistinct("id"));

        if (processInstanceId > 0) {
            criteria.add(Restrictions.eq("processInstance.id", processInstanceId));
        } else if (tokenId > 0) {
            criteria.add(Restrictions.eq("token.id", tokenId));
        } else if (actorIds != null) {
            if (pooledActors) {
                Criteria subcriteria = criteria.createCriteria("pooledActors");

                subcriteria.add(Restrictions.in("actorId", actorIds));
            } else {
                criteria.add(Restrictions.in("actorId", actorIds));
            }
        }

        if (completed != null) {
            if (completed.booleanValue()) {
                criteria.add(Restrictions.isNotNull("end"));
            } else {
                criteria.add(Restrictions.isNull("end"));
            }
        }

        Number count = (Number) criteria.uniqueResult();

        return count.intValue();
    } catch (Exception e) {
        throw new JbpmException(e);
    }
}

From source file:com.liferay.portal.workflow.jbpm.dao.CustomSession.java

License:Open Source License

public List<ProcessInstance> findProcessInstances(long processDefinitionId, Boolean completed, int start,
        int end, OrderByComparator orderByComparator) {

    try {/*from w  ww .  j  a  v a 2  s. com*/
        Criteria criteria = _session.createCriteria(ProcessInstance.class);

        criteria.add(Restrictions.eq("processDefinition.id", processDefinitionId));

        if (completed != null) {
            if (completed.booleanValue()) {
                criteria.add(Restrictions.isNotNull("end"));
            } else {
                criteria.add(Restrictions.isNull("end"));
            }
        }

        addPagination(criteria, start, end);
        addOrder(criteria, orderByComparator);

        return criteria.list();
    } catch (Exception e) {
        throw new JbpmException(e);
    }
}

From source file:com.liferay.portal.workflow.jbpm.dao.CustomSession.java

License:Open Source License

public List<TaskInstance> findTaskInstances(long processInstanceId, long tokenId, String[] actorIds,
        boolean pooledActors, Boolean completed, int start, int end, OrderByComparator orderByComparator) {

    if ((actorIds != null) && (actorIds.length == 0)) {
        return Collections.emptyList();
    }//from   w w w  .java 2 s.c o  m

    try {
        Criteria criteria = _session.createCriteria(TaskInstance.class);

        criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

        if (processInstanceId > 0) {
            criteria.add(Restrictions.eq("processInstance.id", processInstanceId));
        } else if (tokenId > 0) {
            criteria.add(Restrictions.eq("token.id", tokenId));
        }

        if (actorIds != null) {
            if (pooledActors) {
                Criteria subcriteria = criteria.createCriteria("pooledActors");

                subcriteria.add(Restrictions.in("actorId", actorIds));

                criteria.add(Restrictions.isNull("actorId"));
            } else {
                criteria.add(Restrictions.in("actorId", actorIds));
            }
        }

        if (completed != null) {
            if (completed.booleanValue()) {
                criteria.add(Restrictions.isNotNull("end"));
            } else {
                criteria.add(Restrictions.isNull("end"));
            }
        }

        addPagination(criteria, start, end);
        addOrder(criteria, orderByComparator);

        return criteria.list();
    } catch (Exception e) {
        throw new JbpmException(e);
    }
}

From source file:com.liferay.portal.workflow.jbpm.dao.CustomSession.java

License:Open Source License

protected Criteria buildTaskInstanceExtensionSearchCriteria(String taskName, String assetType,
        Long[] assetPrimaryKeys, Date dueDateGT, Date dueDateLT, Boolean completed, Boolean searchByUserRoles,
        boolean andOperator, ServiceContext serviceContext) throws SystemException {

    Criteria criteria = _session.createCriteria(TaskInstanceExtensionImpl.class);

    criteria.createAlias("taskInstance", "taskInstance");

    criteria.add(Restrictions.eq("companyId", serviceContext.getCompanyId()));

    if (Validator.isNotNull(taskName) || Validator.isNotNull(assetType) || (dueDateGT != null)
            || (dueDateLT != null)) {//from w w w  . j a  v a2s.co  m

        Junction junction = null;

        if (andOperator) {
            junction = Restrictions.conjunction();
        } else {
            junction = Restrictions.disjunction();
        }

        if (Validator.isNotNull(taskName)) {
            String[] taskNameKeywords = StringUtil.split(taskName, StringPool.SPACE);

            for (String taskNameKeyword : taskNameKeywords) {
                junction.add(Restrictions.like("taskInstance.name", "%" + taskNameKeyword + "%"));
            }
        }

        if (Validator.isNotNull(assetType)) {
            String[] assetTypeKeywords = StringUtil.split(assetType, StringPool.SPACE);

            for (String assetTypeKeyword : assetTypeKeywords) {
                junction.add(
                        Restrictions.like("workflowContext", "%\"entryType\":\"%" + assetTypeKeyword + "%\"%"));
            }
        }

        if (Validator.isNotNull(assetPrimaryKeys)) {
            for (Long assetPrimaryKey : assetPrimaryKeys) {
                junction.add(Restrictions.like("workflowContext",
                        "%\"entryClassPK\":\"%" + assetPrimaryKey + "%\"%"));
            }
        }

        if (dueDateGT != null) {
            junction.add(Restrictions.ge("taskInstance.dueDate", dueDateGT));
        }

        if (dueDateLT != null) {
            junction.add(Restrictions.lt("taskInstance.dueDate", dueDateGT));
        }

        criteria.add(junction);
    }

    addSearchByUserRolesCriterion(criteria, searchByUserRoles, serviceContext);

    if (completed != null) {
        if (completed.booleanValue()) {
            criteria.add(Restrictions.isNotNull("taskInstance.end"));
        } else {
            criteria.add(Restrictions.isNull("taskInstance.end"));
        }
    }

    return criteria;
}

From source file:com.liferay.portal.workflow.jbpm.dao.CustomSession.java

License:Open Source License

protected Criteria buildProcessInstanceExtensionSearchCriteria(long companyId, Long userId,
        String assetClassName, Long assetClassPK, Boolean completed) {

    Criteria criteria = _session.createCriteria(ProcessInstanceExtensionImpl.class);

    criteria.add(Restrictions.eq("companyId", companyId));

    if (userId != null) {
        criteria.add(Restrictions.eq("userId", userId));
    }//w ww .ja  v  a2  s. com

    if (Validator.isNotNull(assetClassName)) {
        criteria.add(Restrictions.like("className", assetClassName));
    }

    if (Validator.isNotNull(assetClassPK)) {
        criteria.add(Restrictions.eq("classPK", assetClassPK));
    }

    if (completed != null) {
        Criteria completionCriteria = criteria.createCriteria("processInstance");

        if (completed) {
            completionCriteria.add(Restrictions.isNotNull("end"));
        } else {
            completionCriteria.add(Restrictions.isNull("end"));
        }
    }

    return criteria;
}