Example usage for org.hibernate.criterion Projections property

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

Introduction

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

Prototype

public static PropertyProjection property(String propertyName) 

Source Link

Document

A property value projection

Usage

From source file:edu.monash.merc.dao.TrafficLightDAO.java

License:Open Source License

@SuppressWarnings("unchecked")
private List<Long> getAllTrafficLight(TLSearchBean tlSearchBean) {

    String chromType = tlSearchBean.getSelectedChromType();
    int token = tlSearchBean.getCombinatedToken();
    long versionId = tlSearchBean.getSelectedVersion();
    boolean chromRegionProvided = tlSearchBean.isRegionProvided();
    boolean geneListProvided = tlSearchBean.isGeneListProvided();

    boolean typeLevelProvided = tlSearchBean.isTypeLevelProvided();

    Criteria tlCriteria = this.session().createCriteria(this.persistClass);

    if (typeLevelProvided) {
        addTypeColorLevelConditions(tlCriteria, tlSearchBean);
    }//from   w  w  w  . j  a  v  a2 s  . c  om

    Criteria tlGeneCriteria = tlCriteria.createCriteria("tlGene");

    Criteria tpbVersionCriteria = tlCriteria.createCriteria("tpbVersion");
    tlGeneCriteria.add(Restrictions.eq("chromosome", chromType));

    //chromosome region provided
    if (chromRegionProvided) {
        addChromRegionConditions(tlGeneCriteria, tlSearchBean);
    }

    //gene list provided
    if (geneListProvided) {
        addGeneListConditions(tlGeneCriteria, tlSearchBean);
    }

    //tpb version
    tpbVersionCriteria.add(Restrictions.eq("id", versionId));

    tpbVersionCriteria.add(Restrictions.eq("trackToken", token));
    tlCriteria.setProjection(Projections.property("id"));
    return tlCriteria.list();
}

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;//  w  w  w  . j a v  a 2s.  c  o 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.uoc.dao.impl.MeetingRoomDaoImpl.java

@Override
public List<MeetingRoom> findbyForm(SearchMeeting searchMeeting, List<Room> ids_room) {

    String topic = searchMeeting.getTopic();
    Room room = searchMeeting.getRoom();

    //Convert TimeStamp to Date
    Timestamp tsStart = Util.converToTimestamp(searchMeeting.getStart_meeting(), logger);
    Timestamp tsEnd = Util.converToTimestamp(searchMeeting.getEnd_meeting(), logger);

    Criteria criteria;/* w  w  w.j a  v a2  s  .c  o m*/
    criteria = this.getSession().createCriteria(MeetingRoom.class, "meeting");
    criteria.add(Restrictions.eq("meeting.finished", (byte) 1));
    criteria.add(Restrictions.eq("meeting.recorded", (byte) 1));
    if (tsStart != null) {
        criteria.add(Restrictions.ge("meeting.start_meeting", tsStart));
    }
    if (tsEnd != null) {
        criteria.add(Restrictions.le("meeting.end_meeting", tsEnd));
    }
    if (topic != null && topic.length() > 0) {
        criteria.add(Restrictions.like("meeting.topic", "%" + topic + "%"));
    }
    if (room != null && room.getId() > 0) {
        criteria.add(Restrictions.eq("meeting.id_room", room));
    } else {
        criteria.add(Restrictions.in("meeting.id_room", ids_room));
    }
    if (searchMeeting.getParticipants() != null && searchMeeting.getParticipants().length() > 0) {
        DetachedCriteria subCriteria = DetachedCriteria.forClass(UserMeeting.class, "userMeeting");
        subCriteria.createAlias("userMeeting.pk.meeting", "userMeeting.id");
        subCriteria.setProjection(Projections.projectionList().add(Projections.property("userMeeting.id")));
        subCriteria.add(Restrictions.eqProperty("meeting.id", "userMeeting.id"));

        DetachedCriteria subCriteriaUser = DetachedCriteria.forClass(User.class, "user");
        subCriteriaUser.setProjection(Projections.projectionList().add(Projections.property("user.id")));
        subCriteriaUser.add(Restrictions.like("user.fullname", "%" + searchMeeting.getParticipants() + "%"));
        subCriteriaUser.add(Restrictions.eqProperty("user.id", "userMeeting.pk.user.id"));
        subCriteria.add(Subqueries.exists(subCriteriaUser));
        criteria.add(Subqueries.exists(subCriteria));
    }
    logger.info("Criteria " + criteria.toString());

    return criteria.list();
}

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 ww .  j a v  a 2 s  .c  o m
@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: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.
 *
 * @param propertyNames//from w  w w . j  a va  2  s  .  c  o m
 * @param alias
 * @param aliasPath
 * @param domainClass
 * @return
 *
 * @see http://opensource.atlassian.com/projects/hibernate/browse/HHH-817
 */
@Deprecated
public static Projection createAliasedProjectionList(final String[] propertyNames, final String alias,
        final String aliasPath, final Class<?> domainClass) {
    final ProjectionList projectionList = Projections.projectionList();
    for (final String propertyName : propertyNames) {
        final Field field = ReflectionUtils.findField(domainClass, propertyName);
        if (!hasAssociationAnnotation(field)) {
            final String aliasedProperty = alias + "." + propertyName;
            projectionList.add(Projections.property(aliasedProperty), aliasedProperty);
        }
    }
    return projectionList;
}

From source file:edu.utah.further.ds.impl.executor.db.hibernate.criteria.HibernateDistinctEntityExecutor.java

License:Apache License

@Override
public boolean process(final ChainRequest request) {
    final HibernateExecReq execReq = new HibernateExecReq(request);
    final GenericCriteria criteria = execReq.getResult();
    notNull(criteria, "Expected Hibernate criteria");

    final Class<? extends PersistentEntity<?>> domainClass = execReq.getRootEntity();

    final SessionFactory sessionFactory = execReq.getSessionFactory();
    notNull(sessionFactory, "Expected SessionFactory");

    // Get information about the root entity class
    final ClassMetadata classMetadata = sessionFactory.getClassMetadata(domainClass);
    final String[] properties = classMetadata.getPropertyNames();
    final String identifierName = classMetadata.getIdentifierPropertyName();

    final ProjectionList projectionList = Projections.projectionList();
    projectionList.add(Projections.distinct(Projections.property(identifierName)), identifierName);

    // When you use projections, you have to manually specify the selection criteria
    // so we loop through all the properties and specify them here. Note that we skip
    // all the relationship properties (collections).
    for (final String property : properties) {
        final Type type = classMetadata.getPropertyType(property);
        if (!type.isCollectionType()) {
            projectionList.add(Projections.property(property), property);
        }/*www  .  ja va 2 s  .com*/
    }

    criteria.setProjection(projectionList);

    // This turns all of the results into the actual root entity class - calling
    // setters/etc
    criteria.setResultTransformer(new AliasToBeanResultTransformer(domainClass));

    execReq.setResult(criteria);

    return false;
}

From source file:ee.ria.xroad.opmonitordaemon.OperationalDataRecordManager.java

License:Open Source License

private static void setProjectionList(Criteria criteria, Set<String> fields) {
    ProjectionList projList = Projections.projectionList();
    HashSet<String> fieldSet = new HashSet<>(fields);

    // Necessary for searching the records.
    fieldSet.add(MONITORING_DATA_TS);//from w w  w .  j av a2  s. co m

    log.trace("setProjectionList(): {}", fieldSet);

    fieldSet.forEach(i -> projList.add(Projections.property(i), i));

    criteria.setProjection(projList);
    criteria.setResultTransformer(Transformers.aliasToBean(OperationalDataRecord.class));
}

From source file:es.emergya.bbdd.dao.FlotaHome.java

License:Open Source License

@SuppressWarnings("unchecked")
@Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = true, rollbackFor = Throwable.class)
public List<String> getAllIcons() {
    Session currentSession = getSession();
    currentSession.clear();//from   www . j  a va 2  s.  c  o  m
    return (List<String>) currentSession.createCriteria(Flota.class)
            .setProjection(Projections.property("juegoIconos"))
            .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
}

From source file:es.emergya.bbdd.dao.FlotaHome.java

License:Open Source License

@SuppressWarnings("unchecked")
@Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = true, rollbackFor = Throwable.class)
public List<String> getAllNames() {
    Session currentSession = getSession();
    currentSession.clear();/*from  w ww  .  ja v  a  2s  .  c om*/
    return (List<String>) currentSession.createCriteria(Flota.class)
            .setProjection(Projections.property("nombre")).addOrder(Order.asc("nombre"))
            .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
}

From source file:es.emergya.bbdd.dao.FlotaHome.java

License:Open Source License

@SuppressWarnings("unchecked")
@Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = true, rollbackFor = Throwable.class)
public List<String> getAllNamesHabilitadas() {
    Session currentSession = getSession();
    currentSession.clear();//from   w ww .ja  va  2 s  .  c  o  m
    return (List<String>) currentSession.createCriteria(Flota.class)
            .add(Restrictions.eq("habilitada", Boolean.TRUE)).setProjection(Projections.property("nombre"))
            .addOrder(Order.asc("nombre")).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
}