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:edu.psu.iam.cpr.core.messaging.MessagingCore.java

License:Apache License

/**
 * Initialize message notification mapping of notification type to queue list.
 * @param databaseSession contains the database stateless session
 * @param serviceName contains the serviceName
 *///from w  ww  . j a  v a2s .co m
private final void initQueueMap(StatelessSession databaseSession, String serviceName) {

    // Load data from view
    final String notificationSqlQuery = "from VConsumerNotificationDest";
    final Query notificationQuery = databaseSession.createQuery(notificationSqlQuery);
    if (notificationQuery.list().isEmpty()) {
        LOG4J_LOGGER.error(
                "Consumer notification dest view (VConsumerNotificationDest) does not contain any records");
    }

    msgNotificationQueues = new HashMap<String, List<VSpNotification>>();

    // loop through results and create the array map entry for each type
    String previousType = null;
    List<VSpNotification> queueList = new ArrayList<VSpNotification>();
    for (final Iterator<?> it = notificationQuery.list().iterator(); it.hasNext();) {
        VConsumerNotificationDest notificationDbBean = (VConsumerNotificationDest) it.next();

        if (previousType == null) {
            previousType = notificationDbBean.getNotificationType();
        } else if (!previousType.equals(notificationDbBean.getNotificationType())) {
            msgNotificationQueues.put(previousType, queueList);
            previousType = notificationDbBean.getNotificationType();
            queueList = new ArrayList<VSpNotification>();
        }
        Long aConsumer = notificationDbBean.getMessageConsumerKey();
        Query query = databaseSession.createQuery(
                "from VSpNotification where webService = :service_name and message_consumer_key=:consumer");
        query.setParameter("service_name", serviceName);
        query.setParameter("consumer", aConsumer);
        for (Iterator<?> vSp = query.list().iterator(); vSp.hasNext();) {
            VSpNotification vSPNotificationBean = (VSpNotification) vSp.next();
            queueList.add(vSPNotificationBean);
        }
        if (!it.hasNext()) {
            msgNotificationQueues.put(notificationDbBean.getNotificationType(), queueList);
        }
    }

}

From source file:gr.abiss.calipso.service.impl.UserServiceImpl.java

License:Open Source License

@Override
@Transactional(readOnly = false)/*from   w  w  w .j av a2  s . c  o  m*/
public void expireResetPasswordTokens() {
    // get a hibernate session suitable for read-only access to large datasets
    StatelessSession session = ((Session) this.repository.getEntityManager().getDelegate()).getSessionFactory()
            .openStatelessSession();
    Date yesterday = DateUtils.addDays(new Date(), -1);

    // send email notifications for account confirmation tokens that expired
    org.hibernate.Query query = session.createQuery(
            "SELECT new gr.abiss.calipso.model.UserDTO(u.id, u.firstName, u.lastName,u.username, u.email, u.emailHash) FROM User u "
                    + "WHERE u.password IS NULL and u.resetPasswordTokenCreated IS NOT NULL and u.resetPasswordTokenCreated  < :yesterday");
    query.setParameter("yesterday", yesterday);
    query.setFetchSize(Integer.valueOf(1000));
    query.setReadOnly(true);
    query.setLockMode("a", LockMode.NONE);
    ScrollableResults results = query.scroll(ScrollMode.FORWARD_ONLY);
    while (results.next()) {
        UserDTO dto = (UserDTO) results.get(0);
        // TODO: send expiration email
        this.emailService.sendAccountConfirmationExpired(new User(dto));
    }
    results.close();
    session.close();

    // expire tokens, including password reset requests
    this.repository.expireResetPasswordTokens(yesterday);
}

From source file:monasca.thresh.infrastructure.persistence.hibernate.AlarmSqlImpl.java

License:Apache License

@SuppressWarnings("unchecked")
private void getAlarmedMetrics(final StatelessSession session, final Map<String, Alarm> alarmMap,
        final Map<String, String> tenantIdMap, final LookupHelper binder) {

    String rawHQLQuery = "select a.id, md.name as metric_def_name, mdg.id.name, mdg.value, mdg.id.dimensionSetId from MetricDefinitionDb as md, "
            + "MetricDefinitionDimensionsDb as mdd, " + "AlarmMetricDb as am, " + "AlarmDb as a, "
            + "MetricDimensionDb as mdg where md.id = mdd.metricDefinition.id and mdd.id = am.alarmMetricId.metricDefinitionDimensions.id and "
            + "am.alarmMetricId.alarm.id = a.id and mdg.id.dimensionSetId = mdd.metricDimensionSetId and %s";

    final Query query = binder.apply(session.createQuery(binder.formatHQL(rawHQLQuery)));
    final List<Object[]> metricRows = query.list();
    final HashSet<String> existingAlarmId = Sets.newHashSet();
    final Map<String, List<MetricDefinition>> alarmMetrics = this.getAlarmedMetrics(metricRows);

    for (final Object[] row : metricRows) {
        final String alarmId = (String) row[ALARM_ID];
        final Alarm alarm = alarmMap.get(alarmId);
        // This shouldn't happen but it is possible an Alarm gets created after the AlarmDefinition is
        // marked deleted and any existing alarms are deleted but before the Threshold Engine gets the
        // AlarmDefinitionDeleted message
        if (alarm == null) {
            continue;
        }/*from   w w w  . ja va 2 s.  co  m*/
        if (!existingAlarmId.contains(alarmId)) {
            List<MetricDefinition> mdList = alarmMetrics.get(alarmId);
            for (MetricDefinition md : mdList) {
                alarm.addAlarmedMetric(new MetricDefinitionAndTenantId(md, tenantIdMap.get(alarmId)));
            }

        }
        existingAlarmId.add(alarmId);
    }
}

From source file:no.magott.spring.FetchJoinTests.java

License:Apache License

@Test
public void testScrollVsListOnQuery() throws Exception {
    TransactionStatus transaction = transactionManager.getTransaction(new DefaultTransactionDefinition());
    Session session = sessionFactory.getCurrentSession();
    Order order = new Order();
    order.getItems().add(createItem("Product 1"));
    order.getItems().add(createItem("Product 2"));
    order.getItems().add(createItem("Product 3"));
    session.save(order);/*from   ww w .j a v  a2 s . c om*/
    session.flush();
    assertNotNull(order.getId());
    order = new Order();
    order.getItems().add(createItem("Product 4"));
    order.getItems().add(createItem("Product 5"));
    order.getItems().add(createItem("Product 6"));
    session.save(order);
    session.flush();
    assertNotNull(order.getId());
    transactionManager.commit(transaction);

    transaction = transactionManager.getTransaction(new DefaultTransactionDefinition());
    StatelessSession stateless = sessionFactory.openStatelessSession();

    Query query = stateless.createQuery("select o FROM Order AS o LEFT JOIN FETCH o.items");
    int count = query.list().size();

    //Strange!
    assertThat(count, equalTo(6));

    count = getCountFromScrollableResults(query);

    //As expected
    assertThat(count, equalTo(2));

    System.out.println(count);
    transactionManager.commit(transaction);
}

From source file:org.dcm4chee.archive.ejb.query.InstanceQueryImpl.java

License:LGPL

public InstanceQueryImpl(StatelessSession session, IDWithIssuer[] pids, Attributes keys,
        QueryParam queryParam) {//from   w  w w. j  a  va 2 s. c  o  m
    super(query(session, pids, keys, queryParam), false);
    seriesQuery = session.createQuery(QUERY_SERIES_ATTRS);
}

From source file:org.jahia.modules.external.id.ExternalProviderInitializerServiceImpl.java

License:Open Source License

@Override
public void delete(List<String> externalIds, String providerKey, boolean includeDescendants)
        throws RepositoryException {
    if (externalIds.isEmpty()) {
        return;//  w  ww . j  a  v  a2s.c om
    }
    StatelessSession session = null;
    try {
        List<Integer> hashes = new LinkedList<Integer>();
        for (String externalId : externalIds) {
            int hash = externalId.hashCode();
            hashes.add(hash);
        }
        session = hibernateSessionFactory.openStatelessSession();
        session.beginTransaction();

        // delete all
        session.createQuery(
                "delete from UuidMapping where providerKey=:providerKey and externalIdHash in (:externalIds)")
                .setString("providerKey", providerKey).setParameterList("externalIds", hashes).executeUpdate();

        if (includeDescendants) {
            // delete descendants
            Query selectStmt = session
                    .createQuery(
                            "from UuidMapping where providerKey=:providerKey and externalId like :externalId")
                    .setString("providerKey", providerKey);
            for (String externalId : externalIds) {
                selectStmt.setString("externalId", externalId + "/%");
                List<?> descendants = selectStmt.list();

                for (Object mapping : descendants) {
                    UuidMapping m = (UuidMapping) mapping;
                    session.delete(m);
                    invalidateCache(m.getExternalIdHash(), providerKey);
                }
            }
        }

        session.getTransaction().commit();

        for (String externalId : externalIds) {
            int hash = externalId.hashCode();
            invalidateCache(hash, providerKey);
        }
    } catch (Exception e) {
        if (session != null) {
            session.getTransaction().rollback();
        }
        throw new RepositoryException(e);
    } finally {
        if (session != null) {
            session.close();
        }
    }
}

From source file:org.jahia.modules.external.id.ExternalProviderInitializerServiceImpl.java

License:Open Source License

@Override
public String getInternalIdentifier(String externalId, String providerKey) throws RepositoryException {
    int hash = externalId.hashCode();
    String cacheKey = getCacheKey(hash, providerKey);
    String uuid = getIdentifierCache().get(cacheKey) != null
            ? (String) getIdentifierCache().get(cacheKey).getObjectValue()
            : null;//from  www. j av a 2 s .com
    if (uuid == null) {
        StatelessSession session = null;
        try {
            session = getHibernateSessionFactory().openStatelessSession();
            session.beginTransaction();
            List<?> list = session
                    .createQuery("from UuidMapping where providerKey=:providerKey and externalIdHash=:idHash")
                    .setString("providerKey", providerKey).setLong("idHash", hash).setReadOnly(true).list();
            if (list.size() > 0) {
                uuid = ((UuidMapping) list.get(0)).getInternalUuid();
                getIdentifierCache().put(new Element(cacheKey, uuid, true));
            }
            session.getTransaction().commit();
        } catch (Exception e) {
            if (session != null) {
                session.getTransaction().rollback();
            }
            throw new RepositoryException(e);
        } finally {
            if (session != null) {
                session.close();
            }
        }
    }

    return uuid;
}

From source file:org.jahia.modules.external.id.ExternalProviderInitializerServiceImpl.java

License:Open Source License

@Override
public void removeProvider(String providerKey) throws RepositoryException {
    SessionFactory hibernateSession = getHibernateSessionFactory();
    StatelessSession session = null;
    try {/*from  ww w . ja  va2 s.c o m*/
        session = hibernateSession.openStatelessSession();
        session.beginTransaction();
        int deletedCount = session.createQuery("delete from ExternalProviderID where providerKey=:providerKey")
                .setString("providerKey", providerKey).executeUpdate();
        if (deletedCount > 0) {
            logger.info("Deleted external provider entry for key {}", providerKey);
            deletedCount = session.createQuery("delete from UuidMapping where providerKey=:providerKey")
                    .setString("providerKey", providerKey).executeUpdate();
            logger.info("Deleted {} identifier mapping entries for external provider with key {}", deletedCount,
                    providerKey);
        } else {
            logger.info("No external provider entry found for key {}", providerKey);
        }
        session.getTransaction().commit();
    } catch (Exception e) {
        if (session != null) {
            session.getTransaction().rollback();
        }
        throw new RepositoryException(
                "Issue when removing external provider entry and identifier mappings for provider key "
                        + providerKey,
                e);
    } finally {
        if (session != null) {
            session.close();
        }
    }
}

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

License:Open Source License

public String readFile(String filename) throws RepositoryException {
    StatelessSession session = null;
    try {/*  w  w  w .jav a 2 s .c om*/
        session = getHibernateSessionFactory().openStatelessSession();
        session.beginTransaction();
        NodeTypesDBProvider nodeTypesDBProvider = (NodeTypesDBProvider) session
                .createQuery("from NodeTypesDBProvider where filename=:filename")
                .setString("filename", filename).setReadOnly(true).uniqueResult();
        session.getTransaction().commit();
        if (nodeTypesDBProvider != null) {
            return nodeTypesDBProvider.getCndFile();
        }
    } catch (Exception e) {
        if (session != null) {
            session.getTransaction().rollback();
        }
        throw new RepositoryException(e);
    } finally {
        if (session != null) {
            session.close();
        }
    }
    return null;
}

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

License:Open Source License

public List<String> getFilesList() throws RepositoryException {
    StatelessSession session = null;
    try {//  w  w  w  .j ava2 s .c o m
        session = getHibernateSessionFactory().openStatelessSession();
        session.beginTransaction();
        List<String> nodeTypesDBProviderList = session
                .createQuery("select filename from NodeTypesDBProvider order by id").setReadOnly(true).list();
        session.getTransaction().commit();
        if (nodeTypesDBProviderList != null) {
            return nodeTypesDBProviderList;
        }
    } catch (Exception e) {
        if (session != null) {
            session.getTransaction().rollback();
        }
        throw new RepositoryException(e);
    } finally {
        if (session != null) {
            session.close();
        }
    }
    return null;
}