Example usage for org.hibernate StatelessSession createQuery

List of usage examples for org.hibernate StatelessSession createQuery

Introduction

In this page you can find the example usage for org.hibernate StatelessSession createQuery.

Prototype

@Override
    org.hibernate.query.Query createQuery(String queryString);

Source Link

Usage

From source file:org.jahia.services.content.nodetypes.NodeTypesDBServiceImpl.java

License:Open Source License

public void saveCndFile(String filename, String content, Properties properties) throws RepositoryException {
    StatelessSession session = null;
    try {//from w  w w . j a  v a  2s . co  m
        session = getHibernateSessionFactory().openStatelessSession();
        session.beginTransaction();
        NodeTypesDBProvider nodeTypesDBProvider = (NodeTypesDBProvider) session
                .createQuery("from NodeTypesDBProvider where filename=:filename")
                .setString("filename", filename).setReadOnly(false).uniqueResult();
        if (nodeTypesDBProvider != null && content != null) {
            nodeTypesDBProvider.setCndFile(content);
            session.update(nodeTypesDBProvider);
        } else if (nodeTypesDBProvider != null) {
            session.delete(nodeTypesDBProvider);
        } else if (content != null) {
            nodeTypesDBProvider = new NodeTypesDBProvider();
            nodeTypesDBProvider.setFilename(filename);
            nodeTypesDBProvider.setCndFile(content);
            session.insert(nodeTypesDBProvider);
        }

        final StringWriter writer = new StringWriter();
        properties.store(writer, "");

        nodeTypesDBProvider = (NodeTypesDBProvider) session
                .createQuery("from NodeTypesDBProvider where filename=:filename")
                .setString("filename", DEFINITIONS_PROPERTIES).setReadOnly(false).uniqueResult();
        if (nodeTypesDBProvider != null) {
            nodeTypesDBProvider.setCndFile(writer.toString());
            session.update(nodeTypesDBProvider);
        } else {
            nodeTypesDBProvider = new NodeTypesDBProvider();
            nodeTypesDBProvider.setFilename(DEFINITIONS_PROPERTIES);
            nodeTypesDBProvider.setCndFile(writer.toString());
            session.insert(nodeTypesDBProvider);
        }

        session.getTransaction().commit();
    } catch (Exception e) {
        if (session != null) {
            session.getTransaction().rollback();
        }
        throw new RepositoryException(e);
    } finally {
        if (session != null) {
            session.close();
        }
    }
}

From source file:org.jasig.ssp.util.sort.SortingAndPaging.java

License:Apache License

public Pair<Long, Query> applySortingAndPagingToPagedQuery(Object session, final String countColumn,
        final String hqlSelectClause, final StringBuilder hqlWithoutSelect, final boolean filterByStatus,
        String objectToAddStatusFilter, Boolean isInitialRestriction, Map<String, Object> bindParams) {

    if (filterByStatus && StringUtils.isNotBlank(objectToAddStatusFilter)) {
        addStatusFilterToQuery(hqlWithoutSelect, objectToAddStatusFilter, isInitialRestriction);
        bindParams.put("objectStatus", getStatus());
    }//ww  w.ja v a  2 s.  c om

    // When using HQL, subqueries can only occur in the select and the where, not in the from.
    // So we have the client explicitly tell us where the select clause ends and the from+where
    // clause begins so we can unambiguously execute the latter twice, once with our count()
    // function and once for the "real" results. (Parsing to find where the from clause starts is
    // fraught. E.g. see https://issues.jasig.org/browse/SSP-2192 and related tickets.)
    final StringBuilder rowCntHql = new StringBuilder("select ");
    if (StringUtils.isBlank(countColumn)) {
        rowCntHql.append("count(*) ");
    } else {
        rowCntHql.append("count(distinct ").append(countColumn).append(") ");
    }
    rowCntHql.append(hqlWithoutSelect);

    Query fullQuery = null;
    Query rowCntQuery = null;
    final StringBuilder fullHql = new StringBuilder(hqlSelectClause)
            .append(addSortingToQuery(hqlWithoutSelect));
    if (session instanceof Session) {
        Session thisSession = (Session) session;
        fullQuery = addPagingToQuery(thisSession.createQuery(fullHql.toString())).setProperties(bindParams);
        fullQuery = postProcessBindParams(fullQuery, bindParams);
        rowCntQuery = thisSession.createQuery(rowCntHql.toString());
    } else if (session instanceof StatelessSession) {
        StatelessSession thisStatelessSession = (StatelessSession) session;
        fullQuery = addPagingToQuery(thisStatelessSession.createQuery(fullHql.toString()))
                .setProperties(bindParams);
        fullQuery = postProcessBindParams(fullQuery, bindParams);
        rowCntQuery = thisStatelessSession.createQuery(rowCntHql.toString());
    } else {
        throw new IllegalArgumentException(
                "session paramter for org.jasig.ssp.util.sort.SortingAndPaging.applySortingAndPagingToPagedQuery(Object, StringBuilder, boolean, String, Boolean, Map<String, Object>) must "
                        + "must be of type Session or StatelessSession");
    }

    rowCntQuery.setProperties(bindParams);
    rowCntQuery = postProcessBindParams(rowCntQuery, bindParams);
    final Long totalRows = (Long) rowCntQuery.list().get(0);

    // Sorting not added until here b/c if it's present in the count() query
    // above, the db will usually complain about that field not being
    // present in a group by/aggr function
    return new Pair<Long, Query>(totalRows, fullQuery);
}

From source file:org.jboss.seam.wiki.core.nestedset.listener.DeleteNestedSetOperation.java

License:LGPL

protected void executeOnDatabase(StatelessSession ss) {

    Query updateLeft = ss.createQuery(
            "update " + nodeEntityName + " n set " + " n.nodeInfo.nsLeft = n.nodeInfo.nsLeft - :offset "
                    + " where n.nodeInfo.nsThread = :thread and n.nodeInfo.nsLeft > :right");
    updateLeft.setParameter("offset", databaseMoveOffset);
    updateLeft.setParameter("thread", node.getNodeInfo().getNsThread());
    updateLeft.setParameter("right", node.getNodeInfo().getNsRight());
    int updateLeftCount = updateLeft.executeUpdate();
    log.trace("updated left values of nested set nodes: " + updateLeftCount);

    Query updateRight = ss.createQuery(
            "update " + nodeEntityName + " n set " + " n.nodeInfo.nsRight = n.nodeInfo.nsRight - :offset "
                    + " where n.nodeInfo.nsThread = :thread and n.nodeInfo.nsRight > :right");
    updateRight.setParameter("offset", databaseMoveOffset);
    updateRight.setParameter("thread", node.getNodeInfo().getNsThread());
    updateRight.setParameter("right", node.getNodeInfo().getNsRight());
    int updateRightCount = updateRight.executeUpdate();
    log.trace("updated right values of nested set nodes: " + updateRightCount);
}

From source file:org.jboss.seam.wiki.core.nestedset.listener.InsertNestedSetOperation.java

License:LGPL

protected void executeOnDatabase(StatelessSession ss) {
    log.trace("executing nested set insert on database");

    Query updateLeft = ss.createQuery(
            "update " + nodeEntityName + " n set " + " n.nodeInfo.nsLeft = n.nodeInfo.nsLeft + :spaceNeeded "
                    + " where n.nodeInfo.nsThread = :thread and n.nodeInfo.nsLeft > :right");
    updateLeft.setParameter("spaceNeeded", spaceNeeded);
    updateLeft.setParameter("thread", parentThread);
    updateLeft.setParameter("right", newLeft);
    int updateLeftCount = updateLeft.executeUpdate();
    log.trace("updated left values of nested set nodes: " + updateLeftCount);

    Query updateRight = ss.createQuery(
            "update " + nodeEntityName + " n set " + " n.nodeInfo.nsRight = n.nodeInfo.nsRight + :spaceNeeded "
                    + " where n.nodeInfo.nsThread = :thread and n.nodeInfo.nsRight >= :right");
    updateRight.setParameter("spaceNeeded", spaceNeeded);
    updateRight.setParameter("thread", parentThread);
    updateRight.setParameter("right", newLeft);
    int updateRightCount = updateRight.executeUpdate();
    log.trace("updated right values of nested set nodes: " + updateRightCount);

    log.trace("updating the newly inserted row with thread, left, and right values");
    /*/*w ww  .  ja v a 2  s.  c o m*/
    TODO: http://opensource.atlassian.com/projects/hibernate/browse/HHH-1657
    Query updateNode =
        ss.createQuery("update " + nodeEntityName + " n set " +
                       " n.nodeInfo.nsLeft = :left, n.nodeInfo.nsRight = :right, n.nodeInfo.nsThread = :thread " +
                       " where n.id = :id");
     */
    Query updateNode = ss.getNamedQuery("updateNestedSet." + nodeEntityName);

    updateNode.setParameter("thread", parentThread);
    updateNode.setParameter("left", newLeft);
    updateNode.setParameter("right", newRight);
    updateNode.setParameter("id", node.getId());
    updateNode.executeUpdate();
}

From source file:org.ng200.openolympus.services.TaskService.java

License:Open Source License

@PreAuthorize(SecurityExpressionConstants.IS_ADMIN)
@Transactional// www  .j  a v a  2 s.  c  o  m
public void rejudgeTask(final Task task) throws ExecutionException, IOException {

    final Lock lock = task.writeLock();
    lock.lock();

    try {

        this.verdictRepository.flush();
        this.solutionRepository.flush();

        this.verdictRepository.deleteBySolutionTask(task);
        this.verdictRepository.flush();

        final StatelessSession session = ((Session) this.entityManager.getDelegate()).getSessionFactory()
                .openStatelessSession();
        try {
            final Query query = session.createQuery("from Solution where task_id=:taskID");
            query.setParameter("taskID", task.getId());
            query.setFetchSize(Integer.valueOf(1000));
            query.setReadOnly(false);
            final ScrollableResults results = query.scroll(ScrollMode.FORWARD_ONLY);
            try {
                while (results.next()) {
                    final Solution solution = (Solution) results.get(0);
                    this.testingService.testSolutionOnAllTests(solution);
                }
            } finally {
                results.close();
            }
        } finally {
            session.close();
        }
    } finally {
        lock.unlock();
    }
}

From source file:org.openspaces.persistency.hibernate.iterator.HibernateIteratorUtils.java

License:Open Source License

public static Query createQueryFromSQLQuery(SQLQuery<?> sqlQuery, StatelessSession session) {
    String select = sqlQuery.getFromQuery();
    Query query = session.createQuery(select);
    Object[] preparedValues = sqlQuery.getParameters();
    if (preparedValues != null) {
        for (int i = 0; i < preparedValues.length; i++) {
            query.setParameter(i, preparedValues[i]);
        }//from   ww w  . java 2s  . co  m
    }
    query.setReadOnly(true);
    return query;
}

From source file:org.openspaces.persistency.hibernate.iterator.HibernateIteratorUtils.java

License:Open Source License

public static Query createQueryFromDataSourceSQLQuery(DataSourceSQLQuery dataSourceSQLQuery,
        StatelessSession session) {
    String select = dataSourceSQLQuery.getFromQuery();
    Query query = session.createQuery(select);
    Object[] preparedValues = dataSourceSQLQuery.getQueryParameters();
    if (preparedValues != null) {
        for (int i = 0; i < preparedValues.length; i++) {
            query.setParameter(i, preparedValues[i]);
        }/*from www. jav a 2s .c om*/
    }
    query.setReadOnly(true);
    return query;
}

From source file:org.openspaces.persistency.hibernate.StatelessHibernateExternalDataSource.java

License:Open Source License

private void executePartialUpdate(StatelessSession session, BulkItem bulkItem) {
    if (logger.isTraceEnabled()) {
        logger.trace("Partial Update Entry [" + bulkItem.toString() + "]");
    }/*w ww.jav  a 2  s  .  c o m*/

    // filter non mapped properties 
    final Map<String, Object> itemValues = filterItemValue(bulkItem.getTypeName(), bulkItem.getItemValues());

    String hql = getPartialUpdateHQL(bulkItem, itemValues);

    Query query = session.createQuery(hql);

    for (Map.Entry<String, Object> updateEntry : itemValues.entrySet()) {
        query.setParameter(updateEntry.getKey(), updateEntry.getValue());
    }
    query.setParameter("id_" + bulkItem.getIdPropertyName(), bulkItem.getIdPropertyValue());
    query.executeUpdate();
}

From source file:org.openspaces.persistency.hibernate.StatelessHibernateSpaceSynchronizationEndpoint.java

License:Open Source License

private void executePartialUpdate(StatelessSession session, DataSyncOperation dataSyncOperation) {

    if (!dataSyncOperation.supportsDataAsDocument() || !dataSyncOperation.supportsGetTypeDescriptor())
        return;/*from   ww w .j a  va  2 s.c om*/

    if (logger.isTraceEnabled()) {
        logger.trace("Partial Update Entry [" + dataSyncOperation.toString() + ']');
    }

    final SpaceTypeDescriptor typeDescriptor = dataSyncOperation.getTypeDescriptor();
    final String typeName = typeDescriptor.getTypeName();
    // filter non mapped properties 
    SpaceDocument spaceDocument = dataSyncOperation.getDataAsDocument();
    final Map<String, Object> itemValues = filterItemValue(typeName, spaceDocument.getProperties());

    final String hql = getPartialUpdateHQL(dataSyncOperation, itemValues);

    final Query query = session.createQuery(hql);

    for (Map.Entry<String, Object> updateEntry : itemValues.entrySet()) {
        query.setParameter(updateEntry.getKey(), updateEntry.getValue());
    }
    query.setParameter("id_" + typeDescriptor.getIdPropertyName(),
            spaceDocument.getProperty(typeDescriptor.getIdPropertyName()));
    query.executeUpdate();
}

From source file:org.server.core.UserCenter.java

public boolean checkedNameAndPassWord(String name, String password) {
    StatelessSession statelessSession = DataSource.openStatelessSession();
    Userbasicinfo uniqueResult = (Userbasicinfo) statelessSession
            .createQuery("from Userbasicinfo where userName=:name and userPass=md5(:pwd)")
            .setString("name", name).setString("pwd", password).setMaxResults(1).uniqueResult();
    statelessSession.close();/*w  w  w .ja  va2  s.c  om*/
    return uniqueResult != null;
}