Example usage for org.hibernate StatelessSession createSQLQuery

List of usage examples for org.hibernate StatelessSession createSQLQuery

Introduction

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

Prototype

@Override
    NativeQuery createSQLQuery(String queryString);

Source Link

Usage

From source file:com.ephesoft.dcma.core.hibernate.DynamicHibernateDao.java

License:Open Source License

/**
 * To create, update or insert query.//  w ww.ja v  a  2 s  .c o  m
 * 
 * @param session StatelessSession
 * @param queryString String
 * @param params Object
 * @return SQLQuery
 */
public SQLQuery createUpdateOrInsertQuery(StatelessSession session, String queryString, Object... params) {
    SQLQuery sqlQuery = session.createSQLQuery(queryString);

    if (params != null) {
        int pos = 1;
        for (Object p : params) {
            sqlQuery.setParameter(pos++, p);
        }
    }
    return sqlQuery;
}

From source file:com.impetus.client.rdbms.RDBMSClientFactory.java

License:Apache License

@Override
protected Object createPoolOrConnection() {

    getConfigurationObject();/* w w w.  j av a  2 s  .  com*/
    Set<String> pus = kunderaMetadata.getApplicationMetadata().getMetamodelMap().keySet();

    Map<String, Collection<Class<?>>> classes = new HashMap<String, Collection<Class<?>>>();

    for (String pu : pus) {
        classes.put(pu, /* Collection<Class<?>> classes = */((MetamodelImpl) kunderaMetadata
                .getApplicationMetadata().getMetamodel(pu)).getEntityNameToClassMap().values());
    }
    // to keep hibernate happy! As in our case all scanned classes are not
    // meant for rdbms, so initally i have set depth to zero!
    conf.setProperty("hibernate.max_fetch_depth", "0");

    if (externalProperties != null && !externalProperties.isEmpty()) {
        for (String key : externalProperties.keySet()) {
            Object value = externalProperties.get(key);
            if (value instanceof String) {
                conf.setProperty(key, (String) value);
            }
        }
    }

    serviceRegistry = new StandardServiceRegistryBuilder().applySettings(conf.getProperties()).build();

    Iterator<Collection<Class<?>>> iter = classes.values().iterator();

    while (iter.hasNext()) {
        for (Class<?> c : iter.next()) {
            conf.addAnnotatedClass(c);
        }
    }
    sf = conf.buildSessionFactory(serviceRegistry);

    String schemaProperty = conf.getProperty("hibernate.hbm2ddl.auto");
    if (schemaProperty != null && (schemaProperty.equals("create") || schemaProperty.equals("create-drop"))) {
        synchronized (sf) {
            for (String pu : pus) {
                StatelessSession session = sf.openStatelessSession();
                if (!pu.equals(getPersistenceUnit())) {
                    Collection<Class<?>> collection = classes.get(pu);
                    for (Class clazz : collection) {
                        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,
                                clazz);
                        try {
                            session.createSQLQuery("Drop table " + metadata.getTableName()).executeUpdate();
                        } catch (Exception e) {
                            // ignore such drops.
                        }
                    }
                }

            }
        }
    }

    return sf;
}

From source file:mitm.common.hibernate.HibernateUtils.java

License:Open Source License

/**
 * Returns true if the database of the sessionSource is active.
 */// w ww.j a v a2 s  .  c om
public static boolean isDatabaseActive(SessionManager sessionManager, String testQuery) {
    boolean active = false;

    try {
        StatelessSession session = null;

        try {
            session = sessionManager.openStatelessSession();

            SQLQuery query = session.createSQLQuery(testQuery);

            query.list();
        } finally {
            session.close();
        }

        active = true;
    } catch (RuntimeException e) {
        logger.warn("Unable to open a stateless session. Database is probably not active.");
    }

    return active;
}

From source file:monasca.api.infrastructure.persistence.hibernate.AlarmHibernateUtils.java

License:Apache License

public List<String> findAlarmIds(String tenantId, Map<String, String> dimensions) {
    logger.trace(BaseSqlRepo.ORM_LOG_MARKER, "findAlarmIds(...) entering");
    List<String> alarmIdList = null;

    StatelessSession session = null;
    try {//from   www .  ja va2 s .  c  o  m
        session = sessionFactory.openStatelessSession();

        final String sql = this.findAlarmQueryString(dimensions);
        final Query query = session.createSQLQuery(sql).setString("tenantId", tenantId);

        this.bindDimensionsToQuery(query, dimensions);

        @SuppressWarnings("unchecked")
        List<Object[]> rows = query.list();
        alarmIdList = Lists.newArrayListWithCapacity(rows.size());
        for (Object[] row : rows) {
            String id = (String) row[0];
            alarmIdList.add(id);
        }

    } finally {
        if (session != null) {
            session.close();
        }
    }

    // no need to check if alarmIdList != null, because in case of exception method
    // will leave immediately, otherwise list wont be null.
    return alarmIdList;
}

From source file:org.ow2.proactive.db.HibernateDatabaseManager.java

License:Open Source License

/**
 * {@inheritDoc}/*  w w  w. j  av  a2  s . c  o  m*/
 */
@SuppressWarnings("rawtypes")
public List sqlQuery(String nativeQuery) {
    if (!nativeQuery.startsWith("SELECT")) {
        throw new IllegalArgumentException(
                "Native Query string must be a read request, ie:start with 'SELECT'");
    }
    StatelessSession session = getSessionFactory().openStatelessSession();
    try {
        getLogger().debug("Executing query '" + nativeQuery + "'");
        return session.createSQLQuery(nativeQuery).list();
    } catch (Exception e) {
        getLogger().error("", e);
        //this exception will not be handled by exception manager as it is read only and not error prone
        //as it is in a separate thread
        //we let exceptionhandler handle only exception coming from core request
        throw new DatabaseManagerException("Unable to execute sqlQuery !", e);
    } finally {
        closeSession(session);
    }
}

From source file:org.rhq.server.metrics.migrator.workers.AbstractMigrationWorker.java

License:Open Source License

protected void prepareSQLSession(StatelessSession session, DataMigratorConfiguration config) {
    if (DatabaseType.Postgres.equals(config.getDatabaseType())) {
        log.debug("Preparing SQL connection with timeout: " + DataMigrator.SQL_TIMEOUT);

        org.hibernate.Query query = session
                .createSQLQuery("SET LOCAL statement_timeout = " + DataMigrator.SQL_TIMEOUT);
        query.setReadOnly(true);//from   ww  w  . j  ava  2 s  . c om
        query.executeUpdate();
    }
}

From source file:org.rhq.server.metrics.migrator.workers.AggregateDataMigrator.java

License:Open Source License

private long getRowCount(String countQuery) {
    StatelessSession session = getSQLSession(config);

    org.hibernate.Query query = session.createSQLQuery(countQuery);
    query.setReadOnly(true);/*from ww w  .java  2  s.  co  m*/
    query.setTimeout(DataMigrator.SQL_TIMEOUT);
    long count = Long.parseLong(query.uniqueResult().toString());

    closeSQLSession(session);

    return count;
}

From source file:org.rhq.server.metrics.migrator.workers.AggregateDataMigrator.java

License:Open Source License

private void deleteTableData() throws Exception {
    int failureCount = 0;
    while (failureCount < MAX_NUMBER_OF_FAILURES) {
        try {/*from  ww w . j ava  2  s .co  m*/
            StatelessSession session = getSQLSession(config);
            session.getTransaction().begin();
            org.hibernate.Query nativeQuery = session.createSQLQuery(this.deleteQuery);
            nativeQuery.executeUpdate();
            session.getTransaction().commit();
            closeSQLSession(session);
            log.info("- " + migrationTable.toString() + " - Cleaned -");
        } catch (Exception e) {
            log.error("Failed to delete " + migrationTable.toString()
                    + " data. Attempting to delete data one more time...");

            failureCount++;
            if (failureCount == MAX_NUMBER_OF_FAILURES) {
                throw e;
            }
        }
    }
}

From source file:org.rhq.server.metrics.migrator.workers.AggregateDataMigratorTest.java

License:Open Source License

@Test
public void testEstimateTask() throws Exception {
    //tell the method story as it happens: mock or create dependencies and configure
    //those dependencies to get the method under test to completion
    DatabaseType databaseType = DatabaseType.Oracle;
    DataMigratorConfiguration mockConfig = mock(DataMigratorConfiguration.class);
    when(mockConfig.getDatabaseType()).thenReturn(databaseType);

    MetricsIndexMigrator mockMetricsIndexUpdateAccumulator = mock(MetricsIndexMigrator.class);
    PowerMockito.whenNew(MetricsIndexMigrator.class).withArguments(eq(MigrationTable.ONE_HOUR), eq(mockConfig))
            .thenReturn(mockMetricsIndexUpdateAccumulator);

    EntityManager mockEntityManager = mock(EntityManager.class);
    when(mockConfig.getEntityManager()).thenReturn(mockEntityManager);

    org.hibernate.Session mockHibernateSession = mock(org.hibernate.Session.class);
    when(mockEntityManager.getDelegate()).thenReturn(mockHibernateSession);
    SessionFactory mockSessionFactory = mock(SessionFactory.class);
    when(mockHibernateSession.getSessionFactory()).thenReturn(mockSessionFactory);
    StatelessSession mockStatelessSession = mock(StatelessSession.class);
    when(mockSessionFactory.openStatelessSession()).thenReturn(mockStatelessSession);

    org.hibernate.SQLQuery mockQuery = mock(org.hibernate.SQLQuery.class);
    when(mockStatelessSession.createSQLQuery(any(String.class))).thenReturn(mockQuery);

    when(mockQuery.uniqueResult()).thenReturn("1000");

    ScrollableDataSource mockDataSource = mock(ScrollableDataSource.class);
    PowerMockito.whenNew(ScrollableDataSource.class)
            .withArguments(eq(mockEntityManager), eq(databaseType), any(), anyInt()).thenReturn(mockDataSource);
    when(mockDataSource.getData(eq(0), anyInt())).thenReturn(new ArrayList<Object[]>());

    //create object to test and inject required dependencies
    AggregateDataMigrator objectUnderTest = new AggregateDataMigrator(MigrationTable.ONE_HOUR, mockConfig);

    //run code under test
    long estimateActual = objectUnderTest.estimate();

    //verify the results (assert and mock verification)
    PowerMockito.verifyNew(MetricsIndexMigrator.class).withArguments(eq(MigrationTable.ONE_HOUR),
            eq(mockConfig));/* ww w . j  a  v a2  s  .  c  o  m*/
    PowerMockito.verifyNew(ScrollableDataSource.class, times(1)).withArguments(eq(mockEntityManager),
            eq(databaseType), any(), anyInt());

    verify(mockStatelessSession, times(1)).createSQLQuery(any(String.class));
    verify(mockDataSource, times(1)).initialize();
    verify(mockDataSource, times(1)).getData(eq(0), anyInt());
    verify(mockDataSource, times(1)).close();
    verify(mockMetricsIndexUpdateAccumulator, times(1)).drain();

    verifyNoMoreInteractions(mockDataSource);
    verifyNoMoreInteractions(mockMetricsIndexUpdateAccumulator);

    Assert.assertNotEquals(estimateActual, 0);
}

From source file:org.rhq.server.metrics.migrator.workers.AggregateDataMigratorTest.java

License:Open Source License

@Test
public void testMigrateTask() throws Exception {
    //tell the method story as it happens: mock or create dependencies and configure
    //those dependencies to get the method under test to completion
    DatabaseType databaseType = DatabaseType.Oracle;
    DataMigratorConfiguration mockConfig = mock(DataMigratorConfiguration.class);
    when(mockConfig.getDatabaseType()).thenReturn(databaseType);

    Session mockCassandraSession = mock(Session.class);
    when(mockConfig.getSession()).thenReturn(mockCassandraSession);

    MetricsIndexMigrator mockMetricsIndexUpdateAccumulator = mock(MetricsIndexMigrator.class);
    PowerMockito.whenNew(MetricsIndexMigrator.class).withArguments(eq(MigrationTable.ONE_HOUR), eq(mockConfig))
            .thenReturn(mockMetricsIndexUpdateAccumulator);

    EntityManager mockEntityManager = mock(EntityManager.class);
    when(mockConfig.getEntityManager()).thenReturn(mockEntityManager);

    org.hibernate.Session mockHibernateSession = mock(org.hibernate.Session.class);
    when(mockEntityManager.getDelegate()).thenReturn(mockHibernateSession);
    SessionFactory mockSessionFactory = mock(SessionFactory.class);
    when(mockHibernateSession.getSessionFactory()).thenReturn(mockSessionFactory);
    StatelessSession mockStatelessSession = mock(StatelessSession.class);
    when(mockSessionFactory.openStatelessSession()).thenReturn(mockStatelessSession);

    org.hibernate.SQLQuery mockQuery = mock(org.hibernate.SQLQuery.class);
    when(mockStatelessSession.createSQLQuery(any(String.class))).thenReturn(mockQuery);

    when(mockQuery.uniqueResult()).thenReturn("1000");

    ScrollableDataSource mockDataSource = mock(ScrollableDataSource.class);
    PowerMockito.whenNew(ScrollableDataSource.class)
            .withArguments(eq(mockEntityManager), eq(databaseType), any()).thenReturn(mockDataSource);

    List<Object[]> resultList = new ArrayList<Object[]>();
    resultList.add(new Object[] { 100, 100, 100, 100, 100 });
    resultList.add(new Object[] { 100, System.currentTimeMillis() - 100l, 100, 100, 100 });

    for (int index = 0; index < 15; index++) {
        when(mockDataSource.getData(eq(0), anyInt())).thenReturn(resultList);
        when(mockDataSource.getData(eq(2), anyInt())).thenReturn(new ArrayList<Object[]>());
    }//from   www. j  a va 2 s. c  o m

    ResultSetFuture mockResultSetFuture = mock(ResultSetFuture.class);
    when(mockCassandraSession.executeAsync(any(Query.class))).thenReturn(mockResultSetFuture);

    //create object to test and inject required dependencies
    AggregateDataMigrator objectUnderTest = new AggregateDataMigrator(MigrationTable.ONE_HOUR, mockConfig);

    //run code under test
    objectUnderTest.migrate();

    //verify the results (assert and mock verification)
    PowerMockito.verifyNew(MetricsIndexMigrator.class).withArguments(eq(MigrationTable.ONE_HOUR),
            eq(mockConfig));
    PowerMockito.verifyNew(ScrollableDataSource.class, times(1)).withArguments(eq(mockEntityManager),
            eq(databaseType), any());

    verify(mockDataSource, times(1)).initialize();
    verify(mockDataSource, times(1)).getData(eq(0), anyInt());
    verify(mockDataSource, times(1)).getData(eq(2), anyInt());
    verify(mockDataSource, times(1)).close();

    verify(mockMetricsIndexUpdateAccumulator, times(1)).add(eq(100), anyInt());
    verify(mockMetricsIndexUpdateAccumulator, times(1)).drain();

    verify(mockCassandraSession, times(1)).executeAsync(any(Query.class));
    verify(mockResultSetFuture, times(1)).get();

    verifyNoMoreInteractions(mockDataSource);
    verifyNoMoreInteractions(mockCassandraSession);
    verifyNoMoreInteractions(mockResultSetFuture);
    verifyNoMoreInteractions(mockMetricsIndexUpdateAccumulator);
}