Example usage for org.hibernate SessionFactory openStatelessSession

List of usage examples for org.hibernate SessionFactory openStatelessSession

Introduction

In this page you can find the example usage for org.hibernate SessionFactory openStatelessSession.

Prototype

StatelessSession openStatelessSession();

Source Link

Document

Open a new stateless session.

Usage

From source file:org.rhq.server.metrics.migrator.workers.RawDataMigratorTest.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.RAW), 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 });
    resultList.add(new Object[] { 100, System.currentTimeMillis() - 100l, 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   w w  w.jav a2  s. c om*/

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

    //create object to test and inject required dependencies
    RawDataMigrator objectUnderTest = new RawDataMigrator(mockConfig);

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

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

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

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

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

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

From source file:org.squashtest.tm.service.internal.api.repository.HibernateSqlQueryRunner.java

License:Open Source License

private <T> T executeQuery(String selectQuery, QueryExecution<Query> execution) {
    SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
    StatelessSession s = sessionFactory.openStatelessSession();
    Transaction tx = s.beginTransaction();

    T res = null;//from  w  w w .  ja va 2 s.  co m

    try {
        SQLQuery q = s.createSQLQuery(selectQuery);
        res = execution.<T>executeQuery(q);
        tx.commit();
    } catch (HibernateException e) {
        tx.rollback();
        throw e;
    } finally {
        s.close();

    }

    return res;
}

From source file:org.squashtest.tm.service.internal.hibernate.HibernateStatelessSessionHelper.java

License:Open Source License

/**
 * Create a new Hibernate stateless session, by unwrapping the HibernateSessionFactory from EntityManagerFactory and return the session.
 * Don't forget to close it after usage.
 * @return/*from w ww. j  a  va2 s. c om*/
  */
public StatelessSession openStatelessSession() {
    SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
    return sessionFactory.openStatelessSession();
}

From source file:org.transitime.misc.HibernateTest.java

License:Open Source License

/**
 * For comparing timing of doing a large number of inserts. Can either
 * use regular batch mode where there is a specified batch size but
 * the caching and other internal features are still used. Or can
 * use a StatelessSession to bypass all of that internal stuff.
 * This way can easily determine which is the best method.
 * @param cnt/* w w w  .  j a  v a 2 s.co  m*/
 * @param batch
 */
private static void timeBatchStore(int cnt, boolean batch) {
    System.out.println((batch ? "Batch" : "Stateless") + " storing " + cnt + " records");
    IntervalTimer timer = null;

    try {
        SessionFactory sessionFactory = HibernateUtils.getSessionFactory("test");

        // Start timer after session factory is obtained since first time it is
        // obtained it takes a long time. This timer is used to determine how long
        // things take to run.
        timer = new IntervalTimer();

        // Get ready to write
        StatelessSession statelessSession = sessionFactory.openStatelessSession();
        Session batchSession = sessionFactory.openSession();
        System.out.println("Opening session took " + timer.elapsedMsec() + " msec");
        try {
            Transaction tx = batch ? batchSession.beginTransaction() : statelessSession.beginTransaction();

            // Store some AVLReportss
            long initialTime = System.currentTimeMillis();
            for (int i = 0; i < cnt; ++i) {
                AvlReport report = new AvlReport((batch ? "batch" : "stateless") + i, initialTime + i, 1.23,
                        4.56, null);
                if (batch)
                    batchSession.save(report);
                else
                    statelessSession.insert(report);
                if (batch && ((i + 1) % BATCH_SIZE == 0)) {
                    batchSession.flush();
                    batchSession.clear();
                }
            }

            // Finish up writing
            tx.commit();
        } catch (Exception e) {
            // If should rollback the transaction it would be done here
            e.printStackTrace();
        } finally {
            // No matter what, close the session
            batchSession.close();
        }
    } catch (HibernateException e) {
        e.printStackTrace();
    }

    System.out.println((batch ? "Batch" : "Stateless") + " storing " + cnt + " records took "
            + timer.elapsedMsec() + " msec");
}