Example usage for org.hibernate.criterion Restrictions disjunction

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

Introduction

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

Prototype

public static Disjunction disjunction() 

Source Link

Document

Group expressions together in a single disjunction (A or B or C...).

Usage

From source file:org.eurocarbdb.resourcesdb.io.HibernateAccess.java

License:Open Source License

public static ArrayList<Monosaccharide> getMonosaccharideListByFuzzyMonosaccharide(Monosaccharide mono,
        boolean matchCoremodCount, boolean matchSubstCount) {
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    session.beginTransaction();//  w ww  .j a  v  a2s.  co m

    //*** prepare Criteria object: ***
    Criteria query = session.createCriteria(Monosaccharide.class);
    query.createAlias("basetype", "bt");
    if (mono.countCoreModifications() > 0) {
        query.createAlias("bt.coreModifications", "mod");
    }
    if (mono.countSubstitutions() > 0) {
        query.createAlias("substitutions", "subst", Criteria.LEFT_JOIN);
    }

    //*** add restrictions: ***

    Conjunction monoJunc = Restrictions.conjunction();
    query.add(monoJunc);

    //*** size restriction: ***
    if (mono.getSize() > 0) {
        monoJunc.add(Restrictions.eq("bt.size", mono.getSize()));
    }

    //*** stereocode restrictions: ***
    if (mono.getStereoStr() != null && mono.getStereoStr().length() > 0) {
        String stereo1 = null;
        String stereo2 = null;
        if (mono.getStereocode().hasRelativePosition()) {
            try {
                stereo1 = Stereocode.relativeToAbsolute(mono.getStereoStr());
                stereo2 = Stereocode
                        .relativeToAbsolute(Stereocode.changeRelativeDLinStereoString(mono.getStereoStr()));
                stereo2 = stereo2.replaceAll("" + Stereocode.StereoX, "_");
            } catch (ResourcesDbException me) {
                //*** stereocode causes problems, doesn't make sense to use it for search then, therefore nothing needs to be done here ***
                if (Config.getGlobalConfig().isPrintErrorMsgs()) {
                    System.err.println(me);
                    me.printStackTrace();
                }
            }
        } else {
            stereo1 = mono.getStereoStr();
        }
        if (stereo1 != null) {
            stereo1 = stereo1.replaceAll("" + Stereocode.StereoX, "_");
            if (stereo2 != null) {
                monoJunc.add(Restrictions.disjunction().add(Restrictions.like("bt.stereoStr", stereo1))
                        .add(Restrictions.like("bt.stereoStr", stereo2)));
            } else {
                monoJunc.add(Restrictions.like("bt.stereoStr", stereo1));
            }
        }
    }

    //*** anomeric restriction: ***
    if (mono.getAnomer() != null && !mono.getAnomer().equals(Anomer.UNKNOWN)) {
        monoJunc.add(Restrictions.eq("bt.anomerSymbol", mono.getAnomer().getSymbol()));
    }

    //*** ring restrictions: ***
    if (mono.getRingStart() != Basetype.UNKNOWN_RING) {
        monoJunc.add(Restrictions.eq("bt.ringStart", mono.getRingStart()));
    }
    if (mono.getRingEnd() != Basetype.UNKNOWN_RING) {
        monoJunc.add(Restrictions.eq("bt.ringEnd", mono.getRingEnd()));
    }

    //*** core modification restrictions: ***
    if (mono.countCoreModifications() > 0) {
        Conjunction modListConjunct = Restrictions.conjunction();
        for (CoreModification mod : mono.getCoreModifications()) {
            Conjunction modConjunct = Restrictions.conjunction();
            modConjunct.add(Restrictions.eq("mod.name", mod.getName()));
            if (mod.getPosition1().size() > 1) {
                Disjunction modPos1Disjunct = Restrictions.disjunction();
                for (Integer pos1 : mod.getPosition1()) {
                    if (pos1.intValue() != 0) {
                        modPos1Disjunct.add(Restrictions.eq("mod.intValuePosition1", pos1));
                    }
                }
                modConjunct.add(modPos1Disjunct);
            } else if (mod.getIntValuePosition1() > 0) {
                modConjunct.add(Restrictions.eq("mod.intValuePosition1", mod.getIntValuePosition1()));
            }
            if (mod.hasPosition2()) {
                if (mod.getPosition2().size() > 1) {
                    Disjunction modPos2Disjunct = Restrictions.disjunction();
                    for (Integer pos2 : mod.getPosition2()) {
                        if (pos2.intValue() != 0) {
                            modPos2Disjunct.add(Restrictions.eq("mod.intValuePosition2", pos2));
                        }
                    }
                    modConjunct.add(modPos2Disjunct);
                } else if (mod.getIntValuePosition2() > 0) {
                    modConjunct.add(Restrictions.eq("mod.intValuePosition2", mod.getIntValuePosition2()));
                }
            }
            modListConjunct.add(modConjunct);
        }
        monoJunc.add(modListConjunct);
    }

    //*** substitution restrictions: ***
    if (mono.countSubstitutions() > 0) {
        Conjunction substListConjunct = Restrictions.conjunction();
        for (Substitution subst : mono.getSubstitutions()) {
            Conjunction substConjunct = Restrictions.conjunction();
            substConjunct.add(Restrictions.eq("subst.name", subst.getName()));
            if (subst.getPosition1().size() > 1) {
                Disjunction substPos1Disjunct = Restrictions.disjunction();
                for (Integer pos1 : subst.getPosition1()) {
                    if (pos1.intValue() != 0) {
                        substPos1Disjunct.add(Restrictions.eq("subst.intValuePosition1", pos1));
                    }
                }
                substConjunct.add(substPos1Disjunct);
            } else if (subst.getIntValuePosition1() > 0) {
                substConjunct.add(Restrictions.eq("subst.intValuePosition1", subst.getIntValuePosition1()));
            }
            if (subst.getLinkagetype1() != null) {
                substConjunct.add(Restrictions.eq("subst.linkagetypeStr1", subst.getLinkagetypeStr1()));
            }
            if (subst.hasPosition2()) {
                if (subst.getPosition2().size() > 1) {
                    Disjunction substPos2Disjunct = Restrictions.disjunction();
                    for (Integer pos2 : subst.getPosition2()) {
                        if (pos2.intValue() != 0) {
                            substPos2Disjunct.add(Restrictions.eq("subst.intValuePosition2", pos2));
                        }
                    }
                    substConjunct.add(substPos2Disjunct);
                } else if (subst.getIntValuePosition2() > 0) {
                    substConjunct.add(Restrictions.eq("subst.intValuePosition2", subst.getIntValuePosition2()));
                }
                if (subst.getLinkagetype2() != null) {
                    substConjunct.add(Restrictions.eq("subst.linkagetypeStr2", subst.getLinkagetypeStr2()));
                }
            }
            substListConjunct.add(substConjunct);
        }
        monoJunc.add(substListConjunct);
    }

    //*** add "distinct": ***
    query.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

    //System.out.println("query: " + query.toString());

    //*** perform query: ***
    List<?> queryList = query.list();

    //*** prepare result List: ***
    ArrayList<Monosaccharide> resultList = new ArrayList<Monosaccharide>();
    Iterator<?> listIter = queryList.iterator();
    while (listIter.hasNext()) {
        Monosaccharide resultMs = (Monosaccharide) listIter.next();
        if (resultMs != null) {
            //TODO: include modification counts into criteria
            if (!matchCoremodCount || resultMs.countCoreModifications() == mono.countCoreModifications()) {
                if (!matchSubstCount || resultMs.countSubstitutions() == mono.countSubstitutions()) {
                    resultList.add(resultMs);
                }
            }
        }
    }
    return resultList;
}

From source file:org.evolizer.famix.model.utils.SnapshotAnalyzer.java

License:Apache License

/**
 * Query FAMIX entities with a unique name equal the given unique names.
 * /*from w w w.j a  v a 2 s .c o  m*/
 * @param uniqueNames   The given unique names.
 * @return   The list of FAMIX entities equaling the given unique names.
 * @throws EvolizerException
 */
@SuppressWarnings({ "unchecked" })
public List<AbstractFamixEntity> queryEntitiesByUniqueName(List<String> uniqueNames) throws EvolizerException {
    List<AbstractFamixEntity> entities = new ArrayList<AbstractFamixEntity>();

    try {
        Criteria query = getHibernateSession().createCriteria(AbstractFamixEntity.class);
        Disjunction orClausel = Restrictions.disjunction();

        int countOPs = 0;
        for (String uniqueName : uniqueNames) {
            if (uniqueName != "") {
                orClausel.add(Restrictions.eq("uniqueName", uniqueName));
                countOPs++;
            }
        }

        if (countOPs > 0) {
            entities.addAll(query.add(orClausel).list());
        }
    } catch (HibernateException he) {
        fLogger.error("Error in queryEntitiesByUniqueName " + he.getMessage());
        throw new EvolizerRuntimeException("Error in queryEntitiesByUniqueName", he);
    } catch (EvolizerException ee) {
        fLogger.error("Error in queryEntitiesByUniqueName " + ee.getMessage());
        throw new EvolizerRuntimeException("Error in queryEntitiesByUniqueName ", ee);
    }

    return entities;
}

From source file:org.evolizer.famix.model.utils.SnapshotAnalyzer.java

License:Apache License

/**
 * Query FAMIX entities by the source reference as obtained from the Eclipse FamixPackage Explorer.
 * // ww  w .ja  v  a  2s.  c  om
 * @param sourceReferences
 * @return
 * @throws EvolizerException
 */
@SuppressWarnings({ "unchecked" })
public List<AbstractFamixEntity> queryEntitiesBySourceReference(Hashtable<String, Integer> sourceReferences)
        throws EvolizerException {
    List<AbstractFamixEntity> entities = new ArrayList<AbstractFamixEntity>();

    try {
        Criteria query = getHibernateSession().createCriteria(AbstractFamixEntity.class);
        query.createAlias("sourceAnchor", "sa");
        Disjunction orClausel = Restrictions.disjunction();

        int countOPs = 0;
        for (String reducedUniqueName : sourceReferences.keySet()) {
            if (reducedUniqueName != "") {
                orClausel.add(Restrictions.and(Restrictions.like("uniqueName", reducedUniqueName + "(%)"),
                        Restrictions.eq("sa.start", sourceReferences.get(reducedUniqueName))));

                countOPs++;
            }
        }

        if (countOPs > 0) {
            entities.addAll(query.add(orClausel).list());
        }
    } catch (HibernateException he) {
        fLogger.error("Error in queryEntitiesBySourceReference " + he.getMessage());
        throw new EvolizerRuntimeException("Error in queryEntitiesBySourceReference", he);
    } catch (EvolizerException ee) {
        fLogger.error("Error in queryEntitiesBySourceReference " + ee.getMessage());
        throw new EvolizerRuntimeException("Error in queryEntitiesBySourceReference", ee);
    }

    return entities;
}

From source file:org.fornax.cartridges.sculptor.framework.accessimpl.jpahibernate.JpaHibFindByConditionAccessImpl.java

License:Apache License

private Criterion makeCriterion(ConditionalCriteria crit) {
    if (crit == null) {
        return null;
    }//from w  w  w . j av  a  2  s .  c o m

    ConditionalCriteria.Operator operator = crit.getOperator();
    if (Operator.Equal.equals(operator)) {
        return Restrictions.eq(makePathWithAlias(crit.getPropertyFullName()), crit.getFirstOperant());
    } else if (Operator.IgnoreCaseEqual.equals(operator)) {
        return Restrictions.eq(makePathWithAlias(crit.getPropertyFullName()), crit.getFirstOperant())
                .ignoreCase();
    } else if (Operator.LessThan.equals(operator)) {
        return Restrictions.lt(makePathWithAlias(crit.getPropertyFullName()), crit.getFirstOperant());
    } else if (Operator.LessThanOrEqual.equals(operator)) {
        return Restrictions.le(makePathWithAlias(crit.getPropertyFullName()), crit.getFirstOperant());
    } else if (Operator.GreatThan.equals(operator)) {
        return Restrictions.gt(makePathWithAlias(crit.getPropertyFullName()), crit.getFirstOperant());
    } else if (Operator.GreatThanOrEqual.equals(operator)) {
        return Restrictions.ge(makePathWithAlias(crit.getPropertyFullName()), crit.getFirstOperant());
    } else if (Operator.Like.equals(operator)) {
        return Restrictions.like(makePathWithAlias(crit.getPropertyFullName()), crit.getFirstOperant());
    } else if (Operator.IgnoreCaseLike.equals(operator)) {
        return Restrictions.ilike(makePathWithAlias(crit.getPropertyFullName()), crit.getFirstOperant());
    } else if (Operator.IsNull.equals(operator)) {
        return Restrictions.isNull(makePathWithAlias(crit.getPropertyFullName()));
    } else if (Operator.IsNotNull.equals(operator)) {
        return Restrictions.isNotNull(makePathWithAlias(crit.getPropertyFullName()));
    } else if (Operator.IsEmpty.equals(operator)) {
        return Restrictions.isEmpty(makePathWithAlias(crit.getPropertyFullName()));
    } else if (Operator.IsNotEmpty.equals(operator)) {
        return Restrictions.isNotEmpty(makePathWithAlias(crit.getPropertyFullName()));
    } else if (Operator.Not.equals(operator)) {
        return Restrictions.not(makeCriterion((ConditionalCriteria) crit.getFirstOperant()));
    } else if (Operator.Or.equals(operator) && crit.getFirstOperant() instanceof List<?>) {
        Disjunction disj = Restrictions.disjunction();
        List<?> disjList = (List<?>) crit.getFirstOperant();
        for (Object disjPart : disjList) {
            disj.add(makeCriterion((ConditionalCriteria) disjPart));
        }
        return disj;
    } else if (Operator.Or.equals(operator)) {
        return Restrictions.or(makeCriterion((ConditionalCriteria) crit.getFirstOperant()),
                makeCriterion((ConditionalCriteria) crit.getSecondOperant()));
    } else if (Operator.And.equals(operator) && crit.getFirstOperant() instanceof List<?>) {
        Conjunction conj = Restrictions.conjunction();
        List<?> conjList = (List<?>) crit.getFirstOperant();
        for (Object conjPart : conjList) {
            conj.add(makeCriterion((ConditionalCriteria) conjPart));
        }
        return conj;
    } else if (Operator.And.equals(operator)) {
        return Restrictions.and(makeCriterion((ConditionalCriteria) crit.getFirstOperant()),
                makeCriterion((ConditionalCriteria) crit.getSecondOperant()));
    } else if (Operator.In.equals(operator)) {
        if (crit.getFirstOperant() instanceof Collection<?>) {
            return Restrictions.in(makePathWithAlias(crit.getPropertyFullName()),
                    (Collection<?>) crit.getFirstOperant());
        } else {
            return Restrictions.in(makePathWithAlias(crit.getPropertyFullName()),
                    (Object[]) crit.getFirstOperant());
        }
    } else if (Operator.Between.equals(operator)) {
        return Restrictions.between(makePathWithAlias(crit.getPropertyFullName()), crit.getFirstOperant(),
                crit.getSecondOperant());
    } else if (Operator.DistinctRoot.equals(operator)) {
        realDistinctRoot = true;
        return null;
    } else if (Operator.ProjectionRoot.equals(operator)) {
        resultTransformer = Criteria.PROJECTION;
        return null;
    } else if (Operator.EqualProperty.equals(operator)) {
        return Restrictions.eqProperty(makePathWithAlias(crit.getPropertyFullName()),
                (String) crit.getFirstOperant());
    } else if (Operator.LessThanProperty.equals(operator)) {
        return Restrictions.eqProperty(makePathWithAlias(crit.getPropertyFullName()),
                (String) crit.getFirstOperant());
    } else if (Operator.LessThanOrEqualProperty.equals(operator)) {
        return Restrictions.eqProperty(makePathWithAlias(crit.getPropertyFullName()),
                (String) crit.getFirstOperant());
    } else if (Operator.GreatThanProperty.equals(operator)) {
        return Restrictions.eqProperty(makePathWithAlias(crit.getPropertyFullName()),
                (String) crit.getFirstOperant());
    } else if (Operator.GreatThanOrEqualProperty.equals(operator)) {
        return Restrictions.eqProperty(makePathWithAlias(crit.getPropertyFullName()),
                (String) crit.getFirstOperant());
    } else {
        return null;
    }
}

From source file:org.forzaframework.core.persistance.hibernate.BaseDaoHibernate.java

License:Apache License

public List getAll(Class clazz, String query) {
    DetachedCriteria crit = DetachedCriteria.forClass(clazz);
    Disjunction disjunction = Restrictions.disjunction();

    if (StringUtils.isNotBlank(query)) {
        disjunction.add(Restrictions.like("code", query, MatchMode.ANYWHERE).ignoreCase());
        disjunction.add(Restrictions.like("name", query, MatchMode.ANYWHERE).ignoreCase());
    }//w w  w  . ja  va 2 s. co m
    crit.add(disjunction);
    crit.addOrder(Order.asc("id"));

    log.debug("disjunction:" + disjunction.toString());
    return getHibernateTemplate().findByCriteria(crit);
}

From source file:org.foundation.warehouse.ActivePersistenceImpl.java

License:Apache License

public <FoundationalEntity extends Foundation> FoundationalEntity findByProperty(
        Class<? extends Foundation> type, String key, Foundation value) {

    List<FoundationalEntity> foundations = session.createCriteria(type)

            .add(Restrictions.disjunction().add(Restrictions.eq(key + ".id", value.getId()))).list();

    try {/*w  w  w .  j a  v a 2 s. c o  m*/
        return foundations.get(0);
    } catch (IndexOutOfBoundsException e) {
        return null;
    }

    //        return null;
}

From source file:org.foundation.warehouse.ActivePersistenceImpl.java

License:Apache License

public <FoundationalEntity extends Foundation> FoundationalEntity findByLabelId(
        Class<? extends Foundation> type, String id) {

    List<FoundationalEntity> foundations = session.createCriteria(type)

            .add(Restrictions.disjunction().add(Restrictions.eq("name.id", id))).list();

    try {//w  w  w.j  a va2 s .  c o m
        return foundations.get(0);
    } catch (IndexOutOfBoundsException e) {
        return null;
    }

    //        return null;
}

From source file:org.generationcp.middleware.dao.TraitDAO.java

License:Open Source License

@SuppressWarnings("rawtypes")
public Trait getEnvironmentTrait() throws MiddlewareQueryException {
    try {/*from  w  w  w  .java2 s .  c  o m*/
        Criteria crit = getSession().createCriteria(Trait.class);
        crit.add(Restrictions.disjunction().add(Restrictions.eq("name", "environment name"))
                .add(Restrictions.eq("name", "envname")));

        List results = crit.list();

        if (results.isEmpty()) {
            return null;
        } else {
            return (Trait) results.get(0);
        }
    } catch (HibernateException e) {
        throw new MiddlewareQueryException("Error with getEnvironmentTrait() query: " + e.getMessage(), e);
    }
}

From source file:org.generationcp.middleware.dao.TraitDAO.java

License:Open Source License

@SuppressWarnings("rawtypes")
public Trait getDesignTrait() throws MiddlewareQueryException {
    try {//from   www . j  a v a 2s .  c om
        Criteria crit = getSession().createCriteria(Trait.class);
        crit.add(Restrictions.disjunction().add(Restrictions.eq("name", "experimental design"))
                .add(Restrictions.eq("name", "EXPERIMENTAL DESIGN")).add(Restrictions.eq("name", "design")));

        List results = crit.list();

        if (results.isEmpty()) {
            return null;
        } else {
            return (Trait) results.get(0);
        }
    } catch (HibernateException e) {
        throw new MiddlewareQueryException("Error with getDesignTrait() query: " + e.getMessage(), e);
    }
}

From source file:org.glite.security.voms.admin.persistence.dao.hibernate.AuditSearchDAOHibernate.java

License:Apache License

protected Criteria buildCriteriaFromParams(AuditLogSearchParams sp) {

    Criteria crit = createCriteria();/* w  w  w  .  jav a2  s  . c o  m*/

    crit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

    if (sp.getFromTime() != null) {
        crit.add(Restrictions.ge("timestamp", sp.getFromTime()));
    }

    if (sp.getToTime() != null) {
        crit.add(Restrictions.le("timestamp", sp.getToTime()));
    }

    if (sp.getFilterString() != null && !sp.getFilterString().trim().equals("")) {

        if (sp.getFilterType().equals(AuditLogSearchParams.FULL_SEARCH_KEY)) {

            // Full search is basically search over principal
            // and audit event data point values
            String filterString = String.format("%%%s%%", sp.getFilterString());

            // This is due to another ugly limitation of Hibernate 3.3
            // which does not support criteria queries on embedded
            // collections
            // See https://hibernate.atlassian.net/browse/HHH-869

            crit.add(Restrictions.disjunction().add(Restrictions.sqlRestriction(
                    "{alias}.event_id in (select ae.event_id from audit_event ae, audit_event_data aed where ae.event_id = aed.event_id and aed.value like ?)",
                    filterString, StringType.INSTANCE))
                    .add(Restrictions.like("principal", sp.getFilterString().trim(), MatchMode.ANYWHERE)));

        } else {
            crit.add(Restrictions.like(sp.getFilterType(), sp.getFilterString().trim(), MatchMode.ANYWHERE));
        }

    }

    if (sp.getFirstResult() != null) {
        crit.setFirstResult(sp.getFirstResult());
    }

    if (sp.getMaxResults() != null) {
        crit.setMaxResults(sp.getMaxResults());
    }

    crit.addOrder(Order.desc("timestamp"));
    return crit;
}