Example usage for org.hibernate.criterion DetachedCriteria setProjection

List of usage examples for org.hibernate.criterion DetachedCriteria setProjection

Introduction

In this page you can find the example usage for org.hibernate.criterion DetachedCriteria setProjection.

Prototype

public DetachedCriteria setProjection(Projection projection) 

Source Link

Document

Set the projection to use.

Usage

From source file:ru.apertum.qsystem.server.model.QService.java

License:Open Source License

/**
 *  ?  ? ? ? ?  //from   w  w  w  .  j a  v a2s .  c  om
 *
 * @param date  ?   ? ? 
 * @param strictStart false - ? ? ?  ? , true - ? ?  ?  ? ?  date
 * @return ? ? 
 */
public int getAdvancedCount(Date date, boolean strictStart) {
    final GregorianCalendar forDay = new GregorianCalendar();
    forDay.setTime(date);

    final GregorianCalendar today = new GregorianCalendar();
    if (!strictStart && forDay.get(GregorianCalendar.DAY_OF_YEAR) == today.get(GregorianCalendar.DAY_OF_YEAR)
            && day_y != today.get(GregorianCalendar.DAY_OF_YEAR)) {
        day_y = today.get(GregorianCalendar.DAY_OF_YEAR);
        dayAdvs = -100;
    }
    if (!strictStart && forDay.get(GregorianCalendar.DAY_OF_YEAR) == today.get(GregorianCalendar.DAY_OF_YEAR)
            && dayAdvs >= 0) {
        return dayAdvs;
    }

    final DetachedCriteria dc = DetachedCriteria.forClass(QAdvanceCustomer.class);
    dc.setProjection(Projections.rowCount());
    if (!strictStart) {
        forDay.set(GregorianCalendar.HOUR_OF_DAY, 0);
        forDay.set(GregorianCalendar.MINUTE, 0);
    }
    final Date today_m = forDay.getTime();
    forDay.set(GregorianCalendar.HOUR_OF_DAY, 23);
    forDay.set(GregorianCalendar.MINUTE, 59);
    dc.add(Restrictions.between("advanceTime", today_m, forDay.getTime()));
    dc.add(Restrictions.eq("service", this));
    final Long cnt = (Long) (Spring.getInstance().getHt().findByCriteria(dc).get(0));
    final int i = cnt.intValue();

    forDay.setTime(date);
    if (!strictStart && forDay.get(GregorianCalendar.DAY_OF_YEAR) == today.get(GregorianCalendar.DAY_OF_YEAR)) {
        dayAdvs = i;
    }

    QLog.l().logger()
            .trace("? ?  ??  "
                    + getName() + ".  " + i);
    return i;
}

From source file:test.eurocarbdb.dataaccess.core.SubQueryTest.java

License:Open Source License

public void canSimpleDetachedSubQuery() {
    super.setup();

    //Criteria subcriteria = em.createQuery( GlycanSequence.class ).setMaxResults( 20 );
    DetachedCriteria subcriteria = DetachedCriteria.forClass(GlycanSequence.class);

    DetachedCriteria criteria;//from   w  ww . ja v a2  s. co m

    criteria = DetachedCriteria.forClass(GlycanSequence.class);

    //        criteria.add( Restrictions.lt( "glycanSequenceId", 100));
    DetachedCriteria bc_crit = criteria.createCriteria("glycanContexts");

    //DetachedCriteria bc_crit = DetachedCriteria.forClass( GlycanSequenceContext.class );

    //criteria.createCriteria("glycanContexts");

    bc_crit.add(Restrictions.gt("glycanSequenceContextId", 0));
    bc_crit.setProjection(Projections.property("glycanSequenceContextId"));

    criteria.add(Subqueries.propertyIn("glycanSequenceContextId", bc_crit));

    criteria.setProjection(Projections.distinct(Projections.property("glycanSequenceId")));

    subcriteria.add(Subqueries.propertyIn("glycanSequenceId", criteria));

    //System.out.println(subcriteria.list().size());
    //subcriteria.getExecutableCriteria(((HibernateEntityManager) em).getHibernateSession()).setMaxResults(20).list();

    super.teardown();
}

From source file:test.eurocarbdb.dataaccess.core.SubQueryTest.java

License:Open Source License

public void canDetachedSubQuery() {
    super.setup();
    String taxonomyName = "homo sapiens";

    //Criteria subcriteria = em.createQuery( GlycanSequence.class ).setMaxResults( 20 );
    DetachedCriteria subcriteria = DetachedCriteria.forClass(GlycanSequence.class);

    DetachedCriteria criteria;

    criteria = DetachedCriteria.forClass(GlycanSequence.class);

    DetachedCriteria bc_criteria;/* w w  w  . ja va2s .co m*/
    DetachedCriteria tax_criteria;

    bc_criteria = criteria.createCriteria("glycanContexts").createCriteria("biologicalContext", "bc");

    // add taxonomy criteria        
    if (taxonomyName != null) {
        tax_criteria = bc_criteria.createCriteria("taxonomy", "taxa")
                .createCriteria("taxonomySupertypes", "supertax")
                .add(Restrictions.ilike("taxon", taxonomyName, MatchMode.EXACT));
    }

    criteria.setProjection(Projections.distinct(Projections.property("glycanSequenceId")));

    subcriteria.add(Subqueries.propertyIn("glycanSequenceId", criteria));

    //System.out.println(subcriteria.list().size());
    subcriteria.getExecutableCriteria(((HibernateEntityManager) em).getHibernateSession()).list();

    super.teardown();
}

From source file:to.etc.domui.hibernate.model.CriteriaCreatingVisitor.java

License:Open Source License

/**
 * Child-related subquery: determine existence of children having certain characteristics. Because
 * the worthless Hibernate "meta model" API and the utterly disgusting way that mapping data is
 * "stored" in Hibernate we resort to getting the generic type of the child property's collection
 * to determine the type where the subquery is executed on.
 * @see to.etc.webapp.query.QNodeVisitorBase#visitExistsSubquery(to.etc.webapp.query.QExistsSubquery)
 *///from  ww  w .  j a v a  2 s.  c o  m
@Override
public void visitExistsSubquery(QExistsSubquery<?> q) throws Exception {
    String parentAlias = getCurrentAlias();
    Class<?> parentBaseClass = q.getParentQuery().getBaseClass();
    PropertyMetaModel<?> pmm = MetaManager.getPropertyMeta(parentBaseClass, q.getParentProperty());

    //-- If we have a dotted name it can only be parent.parent.parent.childList like (with multiple parents). Parse all parents.
    String childListProperty = q.getParentProperty();
    int ldot = childListProperty.lastIndexOf('.');
    if (ldot != -1) {
        //-- Join all parents, and get the last parent's reference and name
        String last = parseSubcriteria(childListProperty, true); // Create the join path;
        String parentpath = childListProperty.substring(0, ldot); // This now holds parent.parent.parent
        childListProperty = childListProperty.substring(ldot + 1); // And this childList

        //-- We need a "new" parent class: the class that actually contains the "child" list...
        PropertyMetaModel<?> parentpm = MetaManager.getPropertyMeta(parentBaseClass, parentpath);
        parentBaseClass = parentpm.getActualType();

        //-- The above join will have created another alias to the joined table; this is the first part of the "last" reference (which is alias.property).
        ldot = last.indexOf('.');
        if (ldot < 0)
            throw new IllegalStateException("Invalid result from parseSubcriteria inside exists.");
        parentAlias = last.substring(0, ldot);
    }

    //-- Should be List type
    if (!List.class.isAssignableFrom(pmm.getActualType()))
        throw new ProgrammerErrorException("The property '" + q.getParentQuery().getBaseClass() + "."
                + q.getParentProperty() + "' should be a list (it is a " + pmm.getActualType() + ")");

    //-- Make sure there is a where condition to restrict
    QOperatorNode where = q.getRestrictions();
    //      if(where == null)
    //         throw new ProgrammerErrorException("exists subquery has no restrictions: " + this);

    //-- Get the list's generic compound type because we're unable to get it from Hibernate easily.
    Class<?> coltype = MetaManager.findCollectionType(pmm.getGenericActualType());
    if (coltype == null)
        throw new ProgrammerErrorException("The property '" + q.getParentQuery().getBaseClass() + "."
                + q.getParentProperty() + "' has an undeterminable child type");

    //-- 2. Create an exists subquery; create a sub-statement
    DetachedCriteria dc = DetachedCriteria.forClass(coltype, nextAlias());
    Criterion exists = Subqueries.exists(dc);
    dc.setProjection(Projections.id()); // Whatever: just some thingy.

    //-- Append the join condition; we need all children here that are in the parent's collection. We need the parent reference to use in the child.
    ClassMetadata childmd = m_session.getSessionFactory().getClassMetadata(coltype);

    //-- Entering the crofty hellhole that is Hibernate meta"data" 8-(

    ClassMetadata parentmd = m_session.getSessionFactory().getClassMetadata(parentBaseClass);
    int index = findMoronicPropertyIndexBecauseHibernateIsTooStupidToHaveAPropertyMetaDamnit(parentmd,
            childListProperty);
    if (index == -1)
        throw new IllegalStateException(
                "Hibernate does not know property '" + childListProperty + " in " + parentmd.getEntityName());
    Type type = parentmd.getPropertyTypes()[index];
    CollectionType bt = (CollectionType) type;
    final OneToManyPersister persister = (OneToManyPersister) ((SessionFactoryImpl) m_session
            .getSessionFactory()).getCollectionPersister(bt.getRole());
    String[] keyCols = persister.getKeyColumnNames();

    //-- Try to locate those FK column names in the FK table so we can fucking locate the mapping property.
    String childupprop = findCruddyChildProperty(childmd, keyCols);
    if (childupprop == null)
        throw new IllegalStateException("Cannot find child's parent property in crufty Hibernate metadata: "
                + Arrays.toString(keyCols));

    //-- Well, that was it. What a sheitfest. Add the join condition to the parent
    dc.add(Restrictions.eqProperty(childupprop + "." + childmd.getIdentifierPropertyName(),
            parentAlias + "." + parentmd.getIdentifierPropertyName()));

    //-- Sigh; Recursively apply all parts to the detached thingerydoo
    Object old = m_currentCriteria;
    Class<?> oldroot = m_rootClass;
    Map<String, String> oldAliases = m_aliasMap;
    m_aliasMap = new HashMap<String, String>();

    m_rootClass = q.getBaseClass();
    checkHibernateClass(m_rootClass);
    m_currentCriteria = dc;
    if (where != null)
        where.visit(this);
    if (m_last != null) {
        dc.add(m_last);
        m_last = null;
    }
    m_aliasMap = oldAliases;
    m_currentCriteria = old;
    m_rootClass = oldroot;
    m_last = exists;
}

From source file:tw.edu.chit.dao.hibernate.AdminDAOImpl.java

/**
 * //from ww w  . j a  v  a 2s . com
 * @param entity
 * @param example
 * @param criterion
 * @return
 * @throws DataAccessException
 */
@SuppressWarnings("unchecked")
public List getSQLWithCriteria(Class entity, Example example, Projection projection, List<Order> orders,
        int limit, Criterion... criterion) throws DataAccessException {

    DetachedCriteria detachedCriteria = DetachedCriteria.forClass(entity).add(example);
    for (Criterion c : criterion)
        detachedCriteria.add(c);

    if (projection != null)
        detachedCriteria.setProjection(projection);

    if (orders != null && !orders.isEmpty()) {
        for (Order o : orders)
            detachedCriteria.addOrder(o);
    }

    if (limit > -1)
        getHibernateTemplate().setMaxResults(limit);
    else
        getHibernateTemplate().setMaxResults(100000);

    return getHibernateTemplate().findByCriteria(detachedCriteria);
}

From source file:tw.edu.chit.dao.hibernate.AdminDAOImpl.java

/**
 * /*from   w ww  .jav a 2s  . c  o  m*/
 * @param entity
 * @param example
 * @param criterion
 * @return
 * @throws DataAccessException
 */
@SuppressWarnings("unchecked")
public List getSQLWithCriteria(Class entity, Example example, Projection projection, List<Order> orders,
        int limit, List<Criterion> criterion) throws DataAccessException {

    DetachedCriteria detachedCriteria = DetachedCriteria.forClass(entity).add(example);
    for (Criterion c : criterion)
        detachedCriteria.add(c);

    if (projection != null)
        detachedCriteria.setProjection(projection);

    if (orders != null && !orders.isEmpty()) {
        for (Order o : orders)
            detachedCriteria.addOrder(o);
    }

    if (limit > -1) {
        getHibernateTemplate().setMaxResults(limit);
    }

    return getHibernateTemplate().findByCriteria(detachedCriteria);
}

From source file:ubc.pavlab.aspiredb.server.dao.CriteriaBuilder.java

License:Apache License

private static Criterion createCharacteristicCriterion(CharacteristicProperty property, Operator operator,
        TextValue value, EntityType target) {
    DetachedCriteria subquery = DetachedCriteria.forClass(target.clazz);

    addCharacteristicAlias(subquery, target);

    Junction conjunction = Restrictions.conjunction()
            .add(Restrictions.eq("characteristic.key", property.getName()));

    switch (operator) {
    case TEXT_EQUAL:
    case TEXT_NOT_EQUAL:
        conjunction.add(createTextCriterion(operator, "characteristic.value", value.toString()));
        break;//from www .j  a  v  a 2  s  .  c  om
    case NUMERIC_EQUAL:
    case NUMERIC_GREATER:
    case NUMERIC_LESS:
    case NUMERIC_NOT_EQUAL:
        NumericValue numValue = new NumericValue(Integer.valueOf(value.getValue()));
        conjunction.add(createNumericalCriterion(operator, "characteristic.value", numValue));
        break;
    default:
        throw new IllegalArgumentException("Operator type not supported.");
    }

    subquery.add(conjunction);

    subquery.setProjection(Projections.distinct(Projections.id()));
    return Subqueries.propertyIn("id", subquery);
}

From source file:ubc.pavlab.aspiredb.server.dao.CriteriaBuilder.java

License:Apache License

private static Criterion createGenomicRangeCriterion(Operator operator, GenomicRange range, EntityType target) {
    DetachedCriteria subquery = DetachedCriteria.forClass(target.clazz);

    addLocationAlias(subquery, target);//from w  w  w  .j  a v a2s  . c o  m

    subquery.add(overlapsGenomicRegionCriterion(range));

    subquery.setProjection(Projections.distinct(Projections.id()));
    switch (operator) {
    case IS_IN_SET:
        return Subqueries.propertyIn("id", subquery);
    case IS_NOT_IN_SET:
        return Subqueries.propertyNotIn("id", subquery);
    default:
        throw new IllegalArgumentException("Operator not supported.");
    }
}

From source file:ubc.pavlab.aspiredb.server.dao.CriteriaBuilder.java

License:Apache License

private static Criterion createLabelCriterion(LabelProperty property, Operator operator, LabelValueObject value,
        EntityType target) {/*from   w w w. j  ava  2s.  c  o  m*/
    DetachedCriteria subquery = DetachedCriteria.forClass(target.clazz);

    addLabelAlias(subquery, target);

    if (property instanceof VariantLabelProperty) {
        subquery.add(Restrictions.eq("variant_label.id", value.getId()));
    } else if (property instanceof SubjectLabelProperty) {
        subquery.add(Restrictions.eq("subject_label.id", value.getId()));
    }

    subquery.setProjection(Projections.distinct(Projections.id()));

    if (operator == Operator.TEXT_EQUAL) {
        return Subqueries.propertyIn("id", subquery);
    } else if (operator == Operator.TEXT_NOT_EQUAL) {
        return Subqueries.propertyNotIn("id", subquery);
    }

    throw new IllegalArgumentException();
}

From source file:ubc.pavlab.aspiredb.server.dao.CriteriaBuilder.java

License:Apache License

private static Criterion processRestrictionExpression(PhenotypeRestriction restriction, EntityType target) {
    DetachedCriteria subquery = DetachedCriteria.forClass(target.clazz);

    addPhenotypeAlias(subquery, target);

    subquery.add(Restrictions.conjunction().add(Restrictions.eq("phenotype.name", restriction.getName()))
            .add(Restrictions.eq("phenotype.value", restriction.getValue())));

    subquery.setProjection(Projections.distinct(Projections.id()));

    return Subqueries.propertyIn("id", subquery);
}