Example usage for org.hibernate Query setParameterList

List of usage examples for org.hibernate Query setParameterList

Introduction

In this page you can find the example usage for org.hibernate Query setParameterList.

Prototype

Query<R> setParameterList(int position, Object[] values);

Source Link

Usage

From source file:de.userprompt.utils_userweave.query.template.QueryTemplate.java

License:Open Source License

private void setNamedParameterValues(Query hibernateQuery) {
    for (String namedParameter : namedParameter2ConditionValue.keySet()) {
        Object conditionValue = namedParameter2ConditionValue.get(namedParameter);

        if (conditionValue instanceof Collection) {
            hibernateQuery.setParameterList(namedParameter, (Collection) conditionValue);
        } else {/*w  ww. ja v  a  2  s  .co  m*/
            hibernateQuery.setParameter(namedParameter, conditionValue);
        }
    }
}

From source file:dk.statsbiblioteket.medieplatform.workflowstatemonitor.HibernatedStateManager.java

License:Apache License

@Override
public List<State> addState(String entityName, State state, List<String> preservedStates) {
    try {/*w w w.java2 s .  co m*/
        List<State> result = new ArrayList<State>();
        log.trace("Enter addState(entityName='{}',state='{}',preservedStates='{}')",
                new Object[] { entityName, state, preservedStates });
        Session session = HibernateUtil.getSessionFactory().openSession();
        try {
            session.beginTransaction();

            // Get or create entity in database
            Query entityQuery = session.createQuery("from Entity where name = :entityName");
            entityQuery.setParameter("entityName", entityName);
            Entity entity = (Entity) entityQuery.uniqueResult();
            if (entity == null) {
                entity = new Entity();
                entity.setName(entityName);
                session.save(entity);
            }

            // Set entity and date in state
            state.setEntity(entity);
            if (state.getDate() == null) {
                state.setDate(new Date());
            }

            // See if we have a preserved state now
            State preservedState = null;
            if (preservedStates != null && !preservedStates.isEmpty()) {
                Query preservedStateQuery = session.createQuery(
                        "from State s where s.entity.name=:entityName AND s.date = (SELECT MAX(s2.date) FROM State s2 WHERE s.entity.id = s2.entity.id) AND s.stateName IN :preservedStates");
                preservedStateQuery.setParameterList("preservedStates", preservedStates);
                preservedStateQuery.setParameter("entityName", entityName);
                preservedState = (State) preservedStateQuery.uniqueResult();
            }

            // Save the given state
            session.save(state);
            result.add(state);

            // If there was a preserved state, readd it with the current date
            if (preservedState != null) {
                State represervedState = new State();
                represervedState.setDate(new Date());
                represervedState.setMessage(preservedState.getMessage());
                represervedState.setComponent(preservedState.getComponent());
                represervedState.setEntity(preservedState.getEntity());
                represervedState.setStateName(preservedState.getStateName());
                session.save(represervedState);
                result.add(represervedState);
            }

            session.getTransaction().commit();
            log.debug("Added state '{}'", state);
        } catch (RuntimeException e) {
            Transaction transaction = session.getTransaction();
            if (transaction != null && transaction.isActive()) {
                transaction.rollback();
            }
            throw e;
        } finally {
            if (session.isOpen()) {
                session.close();
            }
        }
        log.trace("Exit addState(entityName='{}',state='{}',preservedStates='{} -> {}')",
                new Object[] { entityName, state, preservedStates, result });
        return result;
    } catch (RuntimeException e) {
        log.error("Failed addState(entityName='{}',state='{}',preservedStates='{}')",
                new Object[] { entityName, state, preservedStates, e });
        throw e;
    }
}

From source file:dk.statsbiblioteket.medieplatform.workflowstatemonitor.HibernatedStateManager.java

License:Apache License

private Query buildQuery(Session session, String entityName, boolean onlyLast, List<String> includes,
        List<String> excludes, Date startDate, Date endDate) {
    StringBuilder query = new StringBuilder();
    Map<String, Object> parameters = new HashMap<String, Object>();
    if (entityName != null) {
        initNextClause(query);//from   ww w .j  a v a2  s . c om
        query.append("s.entity.name = :entityName");
        parameters.put("entityName", entityName);
    }

    if (onlyLast) {
        initNextClause(query);
        query.append("s.date = (SELECT MAX(s2.date) FROM State s2 WHERE s.entity.id = s2.entity.id)");
    }

    if (includes != null && includes.size() != 0) {
        initNextClause(query);
        query.append("s.stateName IN (:includes)");
        parameters.put("includes", includes);
    }

    if (excludes != null && excludes.size() != 0) {
        initNextClause(query);
        query.append("NOT s.stateName IN (:excludes)");
        parameters.put("excludes", excludes);
    }

    if (startDate != null) {
        initNextClause(query);
        query.append("s.date >= :startDate");
        parameters.put("startDate", startDate);
    }

    if (endDate != null) {
        initNextClause(query);
        query.append("s.date < :endDate");
        parameters.put("endDate", endDate);
    }

    log.debug("Query: '{}' Parameters: '{}'", query, parameters);
    Query sessionQuery = session
            .createQuery("SELECT s FROM State s " + query.toString() + " ORDER BY s.date DESC");
    for (Map.Entry<String, Object> parameter : parameters.entrySet()) {
        if (parameter.getValue() instanceof Collection) {
            sessionQuery.setParameterList(parameter.getKey(), (Collection) parameter.getValue());
        } else {
            sessionQuery.setParameter(parameter.getKey(), parameter.getValue());
        }
    }
    return sessionQuery;
}

From source file:edu.harvard.med.screensaver.db.hqlbuilder.HqlBuilder.java

License:Open Source License

public Query toQuery(Session session, boolean isReadOnly) {
    org.hibernate.Query query = session.createQuery(toHql());
    for (Map.Entry<String, Object> arg : args().entrySet()) {
        if (arg.getKey().endsWith(SET_ARG_SUFFIX)) {
            // HACK: handle 'list' type parameters, used with the 'IN (?)' operator
            query.setParameterList(arg.getKey(), (Set<?>) arg.getValue());
        } else {//from  ww  w .  ja  v  a  2s  . c o  m
            query.setParameter(arg.getKey(), arg.getValue());
        }
    }
    if (_isDistinctRootEntities) {
        query.setResultTransformer(DistinctRootEntityResultTransformer.INSTANCE);
    }
    query.setReadOnly(isReadOnly);
    return query;
}

From source file:edu.jhuapl.dorset.reporting.SqlReporter.java

License:Open Source License

@Override
public Report[] retrieve(ReportQuery query) {
    Session session = sessionFactory.openSession();
    session.beginTransaction();//from ww  w  .ja  v a  2s  . com
    Query hql = session.createQuery(buildQuery(query)).setParameter("ts_start", query.getStartDate())
            .setParameter("ts_stop", query.getEndDate());
    if (query.getAgentNames() != null) {
        hql.setParameterList("agents", query.getAgentNames());
    }
    if (query.getLimit() != ReportQuery.NO_LIMIT) {
        hql.setMaxResults(query.getLimit());
    }
    @SuppressWarnings("unchecked")
    List<SqlReport> reports = hql.list();
    session.getTransaction().commit();
    session.close();

    // convert to parent Report class for possible serialization
    Report[] rtnReports = new Report[reports.size()];
    for (int i = 0; i < reports.size(); i++) {
        rtnReports[i] = new Report(reports.get(i));
    }
    return rtnReports;
}

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

License:Open Source License

/**
 * {@inheritDoc}/*from   w  w  w .java 2  s.  c o m*/
 */
@SuppressWarnings("unchecked")
public List<Gene> getGenesByDBSChromVersion(DbAcType dbAcType, ChromType chromType, Date versionTime) {

    String gQueryBase = "SELECT g FROM Gene g JOIN g.dbSource dbs WHERE dbs.dbName = :dbName AND g.createdTime = :createdTime AND ";
    List<String> allNamedChroms = ChromType.allNamedChmTypes();
    if (chromType.equals(ChromType.CHMOTHER)) {
        gQueryBase += "g.chromosome NOT IN (:chromosomes)";
    } else {
        gQueryBase += "g.chromosome = :chromosome";
    }

    Query gQuery = this.session().createQuery(gQueryBase);
    gQuery.setString("dbName", dbAcType.type());
    if (chromType.equals(ChromType.CHMOTHER)) {
        gQuery.setParameterList("chromosomes", allNamedChroms);
    } else {
        gQuery.setString("chromosome", chromType.chm());
    }
    gQuery.setTimestamp("createdTime", versionTime);
    return gQuery.list();
}

From source file:edu.psu.iam.cpr.core.database.batch.EduPersonAffiliationCalculator.java

License:Creative Commons License

/**
 * Determines the current set of person affiliations stored in the database for a person
 * @throws CprException will be thrown if there is a Cpr related problem.
 *//*from   ww  w .  j  a v a2  s . c  om*/
public void determineCurrentPersonAffiliations() throws CprException {

    // Fetch the current person affiliations from the database
    final String affiliationSqlQuery = "from PersonAffiliation a where a.personId = :personId AND a.affiliationKey IN (:affiliationKeys) AND endDate IS NULL";
    final Query affiliationQuery = getDatabaseSession().createQuery(affiliationSqlQuery);
    affiliationQuery.setParameterList("affiliationKeys", affiliationKeyList());
    affiliationQuery.setParameter("personId", getPersonId());

    // Clear the person affiliation values
    resetPersonAffiliations();

    // Loop through the affiliation list
    for (final Iterator<?> it = affiliationQuery.list().iterator(); it.hasNext();) {
        PersonAffiliation affiliationDbBean = (PersonAffiliation) it.next();

        if (isEmployeeAffiliationKey(affiliationDbBean.getAffiliationKey())) {
            storeCurrentAffiliation(AffiliationCalculatorKey.EMPLOYEE, affiliationDbBean);
        } else if (isStudentAffiliationKey(affiliationDbBean.getAffiliationKey())) {
            storeCurrentAffiliation(AffiliationCalculatorKey.STUDENT, affiliationDbBean);
        } else if (isMemberAffiliationKey(affiliationDbBean.getAffiliationKey())) {
            storeCurrentAffiliation(AffiliationCalculatorKey.MEMBER, affiliationDbBean);
        }
    }
}

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

License:Open Source License

@Override
public Double getAccNumPropertyScaffold(PropertyDefinition property, AccumulationFunction function,
        Scaffold scaffold, boolean withSubtree) throws DatabaseException {
    Preconditions.checkArgument(!property.isScaffoldProperty(), "Only molecule properties accepted!");
    Preconditions.checkArgument(property.getPropertyType() == PropertyType.NumProperty);

    Double result = 0.0;/* ww w  . j av a 2 s. com*/
    Set<Molecule> molecules = null;
    Session hibernateSession = null;

    if (withSubtree) {
        molecules = new HashSet<Molecule>();
        addChildMolecules(scaffold, molecules);
    } else {
        molecules = scaffold.getMolecules();
    }

    if (molecules.size() == 0)
        throw new IllegalArgumentException("scaffold has no molecules");

    try {
        hibernateSession = sessionFactory.getCurrentSession();
        hibernateSession.beginTransaction();
        String stmt = "";

        switch (function) {
        case Average:
            stmt = "Select avg(prop.value) from MoleculeNumProperty prop where prop.molecule in (:molecules) and type = :type";
            break;
        case Minimum:
            stmt = "Select min(prop.value) from MoleculeNumProperty prop where prop.molecule in (:molecules) and type = :type";
            break;
        case Maximum:
            stmt = "Select max(prop.value) from MoleculeNumProperty prop where prop.molecule in (:molecules) and type = :type";
            break;
        case Sum:
            stmt = "Select sum(prop.value) from MoleculeNumProperty prop where prop.molecule in (:molecules) and type = :type";
            break;
        default:
            throw new DatabaseException("This AccumulationFunction is not supported");
        }
        Query query = hibernateSession.createQuery(stmt);
        query.setParameterList("molecules", molecules);
        query.setParameter("type", property);
        result = (Double) query.uniqueResult();
        hibernateSession.getTransaction().commit();
    } catch (HibernateException ex) {
        logger.error("Querying of accumulated Property failed.\n{}\n{}", ex, stacktrace(ex));
        closeAndRollBackErroneousSession(hibernateSession);
        throw new DatabaseException("Querying of accumulated Property failed", ex);
    }

    return result;
}

From source file:edu.umn.msi.tropix.persistence.dao.hibernate.TropixObjectDaoImpl.java

License:Open Source License

public Set<String> getFilesObjectIds(final Set<String> fileIds) {
    final Set<String> objectIds = Sets.newHashSet();
    for (final Iterable<String> fileIdsPartition : Iterables.partition(fileIds, 100)) {
        final Query query = super.getSession()
                .createQuery("select f.id from TropixFile f where f.fileId in (:fileIds)");
        query.setParameterList("fileIds", Lists.newArrayList(fileIdsPartition));
        @SuppressWarnings("unchecked")
        List<String> partitionObjectIds = query.list();
        objectIds.addAll(partitionObjectIds);
    }/*from w ww . ja va 2  s. co  m*/
    return objectIds;
}

From source file:edu.umn.msi.tropix.persistence.dao.hibernate.TropixObjectDaoImpl.java

License:Open Source License

public Multimap<String, String> getRoles(final String userIdentity, final Iterable<String> objectIds) {
    final Multimap<String, String> roleMap = HashMultimap.create();
    final Iterable<List<String>> objectIdPartitions = Iterables.partition(objectIds, 500);
    for (List<String> objectIdPartition : objectIdPartitions) {
        final Query query = getSession().getNamedQuery("getRolesForObjects");
        query.setParameter("userId", userIdentity);
        query.setParameterList("objectIds", objectIdPartition);
        @SuppressWarnings("unchecked")
        final List<Object[]> results = query.list();
        for (Object[] result : results) {
            roleMap.put((String) result[0], (String) result[1]);
        }/*ww w. j  a v a 2  s .com*/
    }
    return roleMap;
}