Example usage for org.hibernate.criterion Projections id

List of usage examples for org.hibernate.criterion Projections id

Introduction

In this page you can find the example usage for org.hibernate.criterion Projections id.

Prototype

public static IdentifierProjection id() 

Source Link

Document

An identifier value projection.

Usage

From source file:edu.northwestern.bioinformatics.studycalendar.dao.StudySiteDao.java

License:BSD License

@SuppressWarnings({ "unchecked" })
public List<Integer> getIntersectionIds(Collection<Integer> studyIds, Collection<Integer> siteIds) {
    if (studyIds == null && siteIds == null)
        return null;
    return getHibernateTemplate()
            .findByCriteria(createIntersectionCriteria(studyIds, siteIds).setProjection(Projections.id()));
}

From source file:edu.northwestern.bioinformatics.studycalendar.dao.StudySubjectAssignmentDao.java

License:BSD License

@SuppressWarnings({ "unchecked" })
public List<Integer> getAssignmentIdsInIntersection(Collection<Integer> studyIds, Collection<Integer> siteIds) {
    if (studyIds == null && siteIds == null)
        return null;
    return getHibernateTemplate()
            .findByCriteria(createIntersectionCriteria(studyIds, siteIds).setProjection(Projections.id()));
}

From source file:edu.udo.scaffoldhunter.model.db.DbManagerHibernate.java

License:Open Source License

@Override
@SuppressWarnings("unchecked")
public Scaffold getScaffolds(Subset subset, boolean cutStem) throws DatabaseException {
    Preconditions.checkNotNull(subset.getSession());
    Preconditions.checkNotNull(subset.getSession().getTree());

    List<Scaffold> scaffoldList;
    Tree tree = subset.getSession().getTree();
    Session hibernateSession = null;/*from w  w  w .j a v a 2s . co  m*/

    try {
        hibernateSession = sessionFactory.getCurrentSession();
        hibernateSession.beginTransaction();
        // loading the whole tree and then throwing away the scaffolds we
        // don't need seems to be much faster than retrieving only the
        // scaffolds with generation molecules in the current subset
        Criteria criteriaScaf = hibernateSession.createCriteria(Scaffold.class)
                .add(Restrictions.eq("tree", tree));
        scaffoldList = criteriaScaf.list();
    } catch (HibernateException ex) {
        logger.error("Query from Scaffold failed.\n{}\n{}", ex, stacktrace(ex));
        closeAndRollBackErroneousSession(hibernateSession);
        throw new DatabaseException("Query from Scaffold failed", ex);
    }

    Map<Integer, Molecule> mols = new HashMap<Integer, Molecule>();
    Set<Molecule> subMols = subset.getMolecules();
    for (Molecule m : subMols)
        mols.put(m.getId(), m);

    Set<Scaffold> scaffolds = Sets.newHashSet();

    /*
     * determine which scaffolds have molecules in the subset and add
     * molecules to scaffolds
     */
    try {
        hibernateSession = sessionFactory.getCurrentSession();

        /*
         * load tuples (ScaffoldId, GenerationMoleculeId) for the current
         * tree
         */
        Criteria criteria = hibernateSession.createCriteria(Scaffold.class)
                .createAlias("generationMolecules", "mols").add(Restrictions.eq("tree", tree))
                .setProjection(Projections.projectionList().add(Projections.id())
                        .add(Projections.property("mols.id")));

        List<Object[]> tuples = criteria.list();
        Multimap<Integer, Molecule> scaffoldMolecules = HashMultimap.create(scaffoldList.size(), 10);
        for (Object[] t : tuples) {
            Molecule mol = mols.get(t[1]);
            if (mol != null)
                scaffoldMolecules.put((Integer) t[0], mol);
        }

        for (Scaffold s : scaffoldList) {
            if (!scaffoldMolecules.containsKey(s.id))
                continue;
            Collection<Molecule> subScafMols = scaffoldMolecules.get(s.id);
            s.setMolecules(Sets.newHashSet(subScafMols));
            scaffolds.add(s);
        }

        hibernateSession.getTransaction().commit();
    } catch (HibernateException ex) {
        logger.error("Query from Molecule failed.\n{}\n{}", ex, stacktrace(ex));
        closeAndRollBackErroneousSession(hibernateSession);
        throw new DatabaseException("Query from Molecule failed", ex);
    }

    /*
     * add parent scaffolds to the set, that do not have molecules and thus
     * were not returned from the database
     */
    Set<Scaffold> parents = new HashSet<Scaffold>();
    for (Scaffold s : scaffolds) {
        addParents(s, parents, scaffolds);
    }
    scaffolds.addAll(parents);

    if (scaffolds.isEmpty())
        return null;

    Scaffold root = Scaffolds.getRoot(scaffolds.iterator().next());
    Scaffolds.sort(root, Orderings.STRUCTURE_BY_ID);

    for (Scaffold s : Scaffolds.getSubtreePreorderIterable(root)) {
        s.setTree(tree);
    }
    // remove the imaginary root if it has only one child
    if (root.getChildren().size() == 1) {
        root = root.getChildren().get(0);
        root.setParent(null);
    }
    // remove virtual root scaffolds with only one child
    while (cutStem && root.getChildren().size() == 1 && root.getMolecules().isEmpty()) {
        root = root.getChildren().get(0);
    }
    root.setParent(null);
    return root;
}

From source file:edu.utah.further.core.data.util.HibernateUtil.java

License:Apache License

/**
 * @deprecated This method does not work well due to Hibernate bug HHH-817, nor does
 *             AliasToBeanResultTransformer handle multi-level property values.
 *             Therefore it should not be used.
 * @see http://opensource.atlassian.com/projects/hibernate/browse/HHH-817
 *//* w  w w.java  2  s.com*/
@Deprecated
public static Projection createProjectionList(final String identifierProperty, final Type identifierType,
        final String[] propertyNames, final Class<?> domainClass) {
    final ProjectionList projectionList = Projections.projectionList();
    if (identifierType.isComponentType()) {
        final String[] idProperties = ((ComponentType) (identifierType)).getPropertyNames();
        for (final String idProperty : idProperties) {
            final String idPath = identifierProperty + "." + idProperty;
            projectionList.add(Projections.property(idPath));
        }
    } else {
        projectionList.add(Projections.id());
    }
    for (final String propertyName : propertyNames) {
        final Field field = ReflectionUtils.findField(domainClass, propertyName);
        if (!hasAssociationAnnotation(field)) {
            projectionList.add(Projections.property(propertyName), propertyName);
        }

    }
    return projectionList;
}

From source file:es.udc.tfg_es.clubtriatlon.utils.dao.GenericDaoHibernate.java

License:BSD License

public boolean exists(PK id) {
    return getSession().createCriteria(entityClass).add(Restrictions.idEq(id)).setProjection(Projections.id())
            .uniqueResult() != null;
}

From source file:gov.nih.nci.security.upt.util.HibernateHelper.java

License:BSD License

private static Criteria createCriterias(FilterClause filterClause, Session session) {
    List<Criteria> criteriaList = new ArrayList();
    criteriaList.add(0, session.createCriteria(filterClause.getClassName()));
    StringTokenizer stringTokenizer = new StringTokenizer(filterClause.getFilterChain(), ",");
    int count = 0;
    while (stringTokenizer.hasMoreTokens()) {
        String attributeName = stringTokenizer.nextToken();
        if (attributeName.trim().equals(filterClause.getClassName()))
            break;
        count++;/*from   www.  ja v  a  2 s  .  co  m*/
        Criteria parentCriteria = criteriaList.get(count - 1);
        Criteria childCriteria = parentCriteria.createCriteria(attributeName.trim());
        criteriaList.add(count, childCriteria);
    }
    Criteria targetCriteria = criteriaList.get(count);
    String attributeName = filterClause.getTargetClassAttributeName();
    Class attributeType = null;
    Class IntegerType = null;
    try {
        attributeType = Class.forName(filterClause.getTargetClassAttributeType());
        IntegerType = Class.forName("java.lang.Integer");
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    Object valueArray = Array.newInstance(attributeType, 1);

    try {
        if (attributeType.equals(IntegerType)) {
            Array.set(valueArray, 0, new Integer(0));
        } else {
            Array.set(valueArray, 0, attributeType.newInstance());
        }
    } catch (ArrayIndexOutOfBoundsException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }

    targetCriteria.add(Expression.in(attributeName, (Object[]) valueArray));
    Criteria mainCriteria = (Criteria) criteriaList.get(0);
    mainCriteria.setProjection(Projections.id());

    return mainCriteria;
}

From source file:grails.orm.HibernateCriteriaBuilder.java

License:Apache License

public org.grails.datastore.mapping.query.api.Projections id() {
    final IdentifierProjection proj = Projections.id();
    addProjectionToList(proj, null);//from   w ww  .j av  a  2 s.  c om
    return this;
}

From source file:kr.debop4j.data.hibernate.tools.EntityTool.java

License:Apache License

/**
 * Get ancestors id criteria.//from ww w  .ja  v  a2s.c o  m
 *
 * @param entity      the entity
 * @param session     the session
 * @param entityClass the entity class
 * @return the detached criteria
 */
public static <T extends IHierarchyEntity<T> & IEntity<TId>, TId extends Serializable> DetachedCriteria getAncestorsIdCriteria(
        T entity, Session session, Class<T> entityClass) {
    return getAncestorsCriteria(entity, session, entityClass)
            .setProjection(Projections.distinct(Projections.id()));
}

From source file:kr.debop4j.data.hibernate.tools.EntityTool.java

License:Apache License

/**
 * Get descendents id criteria./*  w w  w.j  av a2  s . co m*/
 *
 * @param entity      the entity
 * @param session     the session
 * @param entityClass the entity class
 * @return the detached criteria
 */
public static <T extends IHierarchyEntity<T> & IEntity<TId>, TId extends Serializable> DetachedCriteria getDescendentsIdCriteria(
        T entity, Session session, Class<T> entityClass) {
    return getDescendentsCriteria(entity, session, entityClass)
            .setProjection(Projections.distinct(Projections.id()));
}

From source file:net.firejack.platform.core.store.AbstractStore.java

License:Apache License

@Override
@Transactional(readOnly = true)//from  ww w. j  a v  a2 s . co  m
public <I extends Serializable> Map<I, ID> searchKeys(String key, Collection<I> values) {
    if (!values.isEmpty()) {
        Criteria criteria = getSession().createCriteria(getClazz());
        criteria.add(generateInRestriction(key, values));
        ProjectionList projectionList = Projections.projectionList();
        projectionList.add(Projections.property(key));
        projectionList.add(Projections.id());

        criteria.setProjection(projectionList);

        List<Object[]> list = (List<Object[]>) criteria.list();

        Map<I, ID> search = new HashMap<I, ID>(list.size());
        for (Object[] item : list) {
            search.put((I) item[0], (ID) item[1]);
        }
        return search;
    }
    return Collections.emptyMap();
}