Example usage for org.hibernate.criterion Projections projectionList

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

Introduction

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

Prototype

public static ProjectionList projectionList() 

Source Link

Document

Create a new projection list.

Usage

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

License:BSD License

public int getCountBySource(String source) {
    return (Integer) CollectionUtils.firstElement(getSession().createCriteria(Activity.class)
            .setProjection(Projections.projectionList().add(Projections.rowCount()))
            .add(Restrictions.eq("source", source)).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;/*from 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;/*from w w w .j av a  2s .  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
 *//*from  w w w  .  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 va2s. co 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);
        }//from   www .ja  v a  2s  .c  o  m
    }

    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:edu.utah.further.ds.impl.executor.db.hibernate.criteria.HibernateDistinctIdExecutor.java

License:Apache License

/**
 * @param request/*from  ww w  .j  a  va 2  s. c  o m*/
 * @return
 * @see edu.utah.further.core.chain.AbstractRequestHandler#process(edu.utah.further.core.api.chain.ChainRequest)
 * @see http://opensource.atlassian.com/projects/hibernate/browse/HHH-817
 */
@Override
public boolean process(final ChainRequest request) {
    final HibernateExecReq executionReq = new HibernateExecReq(request);

    // Validate required input
    final GenericCriteria hibernateCriteria = executionReq.getResult();
    notNull(hibernateCriteria, "Expected Hibernate criteria");

    final Class<? extends PersistentEntity<?>> domainClass = executionReq.getRootEntity();
    final Class<? extends PersistentEntity<?>> entityClass = dao.getEntityClass(domainClass);

    notNull(entityClass, "Expected root entity class");

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

    final ClassMetadata classMetadata = sessionFactory.getClassMetadata(entityClass);
    final String identifierName = classMetadata.getIdentifierPropertyName();
    final Type identifierType = classMetadata.getIdentifierType();

    // A hack to obtain projections out of the critieria by casting to the Hibernate
    // implementation. TODO: improve adapter to do that via interface access
    final ProjectionList projectionList = Projections.projectionList();
    final Projection existingProjection = ((CriteriaImpl) hibernateCriteria.getHibernateCriteria())
            .getProjection();

    if (existingProjection != null && !overrideExistingProjection) {
        return false;
    }

    if (identifierType.isComponentType()) {
        final ComponentType componentType = (ComponentType) identifierType;
        final String[] idPropertyNames = componentType.getPropertyNames();

        // Add distinct to the first property
        projectionList.add(
                Projections
                        .distinct(Property.forName(identifierName + PROPERTY_SCOPE_CHAR + idPropertyNames[0])),
                idPropertyNames[0]);

        // Add the remaining properties to the projection list
        for (int i = 1; i < idPropertyNames.length; i++) {
            projectionList.add(Property.forName(identifierName + PROPERTY_SCOPE_CHAR + idPropertyNames[i]),
                    idPropertyNames[i]);
        }

        hibernateCriteria.setProjection(projectionList);
        hibernateCriteria.setResultTransformer(new AliasToBeanResultTransformer(
                ReflectionUtils.findField(entityClass, identifierName).getType()));
    } else {
        // 'this' required to avoid HHH-817
        projectionList.add(Projections.distinct(Property.forName(THIS_CONTEXT + identifierName)));
        hibernateCriteria.setProjection(projectionList);
    }

    executionReq.setResult(hibernateCriteria);

    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);/*  w ww .ja v  a  2 s.c om*/

    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.itecban.deployment.environmentmanager.manager.AgentConnector.java

License:Apache License

/**
 * Connects to a TM with a specific ip address. The port by default is 1155
 * @param environmentname/*from   w w w  .  ja  v  a  2s  .  c o m*/
 * @return the TargetManager MXBean
 * @throws Exception 
 */

protected static TargetManagerMXBean connect2TM(String environmentname, String dirIp, String port,
        SessionFactory sessionFactory) throws Exception {

    if (dirIp == null) {
        final Session session = sessionFactory.openSession();
        session.beginTransaction();
        try {
            // Get the latest date for the "photos" stored in the database
            Criteria timestampCriteria = session.createCriteria(DeploymentTargetType.class);
            timestampCriteria.setProjection(Projections.projectionList().add(Projections.max("timestamp")));
            timestampCriteria.add(Restrictions.eq("name", environmentname));
            Object lastEvironmentTimestampCriteria = timestampCriteria.uniqueResult();
            if (lastEvironmentTimestampCriteria == null)
                throw new Exception("There is no environment with that name in the database");
            //TODO: cambiar cuando el TM este actualizado en indra
            String qSelect = "select dtt.uUID from DeploymentTargetType as dtt"
                    + " where dtt.timestamp=:timestamp and" + " dtt.name=:environmentName";
            Query query = session.createQuery(qSelect);
            query.setParameter("timestamp", lastEvironmentTimestampCriteria);
            query.setString("environmentName", environmentname);
            dirIp = (String) query.uniqueResult();
        } catch (Exception e) {
            System.err.println("Error while retrieving the ip to connect via JMX");
            e.printStackTrace();
        } finally {
            session.close();
        }
    }
    if (port == null)
        port = "1155";
    String serviceurl = "service:jmx:rmi:///jndi/rmi://" + dirIp + ":" + port + "/TargetManager";
    logger.info("JMX direction: " + serviceurl);

    TargetManagerMXBean targetmanagermxbean = null;
    try {
        //checks if the connection is already established (in the connectionTable)
        MBeanServerConnection mBeanServerConnection = null;
        if (!connectionTable.containsKey(serviceurl)) {
            //the connection does not exist. Creating the new connection
            JMXConnector jmxconnector = JMXConnectorFactory.connect(new JMXServiceURL(serviceurl));
            mBeanServerConnection = jmxconnector.getMBeanServerConnection();
            targetmanagermxbean = JMX.newMXBeanProxy(mBeanServerConnection,
                    new ObjectName(Constants.TM_OBJECT_NAME), TargetManagerMXBean.class);
            logger.info("New connection created to TargetManager with name: " + targetmanagermxbean.getName());
            connectionTable.put(serviceurl, mBeanServerConnection);
        } else {
            mBeanServerConnection = (MBeanServerConnection) connectionTable.get(serviceurl);
            try {
                targetmanagermxbean = JMX.newMXBeanProxy(mBeanServerConnection,
                        new ObjectName(Constants.TM_OBJECT_NAME), TargetManagerMXBean.class);
                if (targetmanagermxbean == null || !targetmanagermxbean.isactive())
                    throw new Exception();
                logger.info("Connection obtained to TargetManager with name: " + targetmanagermxbean.getName());

            } catch (Exception e) {
                logger.info("Recreating the connection to TargetManager");
                //maybe the connection to the target manager has been closed so it must be created again
                try {
                    JMXConnector jmxconnector = JMXConnectorFactory.connect(new JMXServiceURL(serviceurl));
                    mBeanServerConnection = jmxconnector.getMBeanServerConnection();
                    targetmanagermxbean = JMX.newMXBeanProxy(mBeanServerConnection,
                            new ObjectName(Constants.TM_OBJECT_NAME), TargetManagerMXBean.class);
                    if (targetmanagermxbean == null || !targetmanagermxbean.isactive())
                        throw new Exception();
                    connectionTable.put(serviceurl, mBeanServerConnection);
                    logger.info("Connection recreated to TargetManager with name: "
                            + targetmanagermxbean.getName());
                } catch (Exception e1) {
                    logger.severe("Impossible to recreate the connection to the TargetManager with name: "
                            + targetmanagermxbean.getName());
                    e1.printStackTrace();
                }
            }
        }
    } catch (Exception e) {
        logger.severe("Problem while connecting to the targetmanager via JMX " + e);
        throw new Exception("running.error.tm.connection");
    }
    return targetmanagermxbean;
}

From source file:es.itecban.deployment.environmentmanager.manager.DBCleanerImpl.java

License:Apache License

/**
 * Cleans all the photos of a date interval
 *///w  ww  .  j ava  2 s . com

// @Override
// public int clean(XMLGregorianCalendar minDate, XMLGregorianCalendar
// maxDate) throws Exception {
//
// logger.info("Beginning the cleannin of data.");
// final Session session = this.sessionFactory.openSession();
// int i = 0;
// List<DeploymentTargetType> environmentList = null;
// try {
// Criteria dttCriteria = session
// .createCriteria(DeploymentTargetType.class);
// // cuando no hay fecha es null o es ""??
// if (minDate != null)
// dttCriteria.add(Restrictions.ge("timestamp", minDate));
// if (maxDate != null)
// dttCriteria.add(Restrictions.le("timestamp", maxDate));
// dttCriteria.setMaxResults(3);
// boolean more = true;
//         
// while (more){
// session.beginTransaction();
// environmentList = dttCriteria.setMaxResults(3).list();
// if (environmentList.size() < 3)
// more = false;
// for (DeploymentTargetType environment : environmentList) {
// session.delete(environment);
// i++;
// }
// // Check if there is more to delete
// session.getTransaction().commit();
//            
// }
// } catch (Exception e) {
// logger.severe("Error while deleting the environment from the database"
// + e);
// throw new Exception(
// "Error while deleting the environment from the database" + e);
// } finally {
// session.close();
// }
// logger.info("Finished the cleannin of data.");
// return i;
// }
private Object getLastEnvironmentDayDate(String environmentName, XMLGregorianCalendar minDate,
        XMLGregorianCalendar maxDate) {

    final Session session = this.sessionFactory.openSession();
    session.beginTransaction();

    // Get the latest date for the "photos" stored in the database
    Criteria timestampCriteria = session.createCriteria(DeploymentTargetType.class);

    if (minDate != null)
        timestampCriteria.add(Restrictions.ge("timestamp", minDate));
    if (maxDate != null)
        timestampCriteria.add(Restrictions.lt("timestamp", maxDate));

    timestampCriteria.setProjection(Projections.projectionList().add(Projections.max("timestamp")));
    timestampCriteria.add(Restrictions.eq("name", environmentName));
    Object lastEvironmentTimestampCriteria = timestampCriteria.uniqueResult();

    session.close();
    return lastEvironmentTimestampCriteria;
}