Example usage for org.hibernate SessionFactory withOptions

List of usage examples for org.hibernate SessionFactory withOptions

Introduction

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

Prototype

SessionBuilder withOptions();

Source Link

Document

Obtain a Session builder.

Usage

From source file:com.sam.moca.db.hibernate.HibernateTools.java

License:Open Source License

/**
 * Session factory method that allows for an interceptor object to be passed.
 * The session created with this method will use the interceptor as passed
 * if the session was not previously created.
 * @param ctx//from www.j  a va 2 s.com
 * @param interceptor
 * @return
 */
public static Session getSession(MocaContext ctx, Interceptor interceptor) {
    Session session = (Session) ctx.getTransactionAttribute(SESSION_ATTRIBUTE_NAME);
    if (session == null) {
        DatabaseTool db = ctx.getDb();
        SessionFactory factory = getSessionFactory(ctx);
        // We cannot use getCurrentSession, due to our use of locally scoped
        // interceptors.  The getCurrentSession method only works with
        // a globally scoped interceptor.
        Connection conn = db.getConnection();
        session = factory.withOptions().connection(conn).interceptor(interceptor).openSession();
        ctx.setTransactionAttribute(SESSION_ATTRIBUTE_NAME, session);

        TransactionHook sessionHook = new _SessionFlushHook(session);
        ctx.addTransactionHook(sessionHook);
    }

    return session;
}

From source file:demo.fabric.HibernateFabric.java

License:Open Source License

public static void main(String args[]) throws Exception {

    String hostname = System.getProperty("com.mysql.fabric.testsuite.hostname");
    String port = System.getProperty("com.mysql.fabric.testsuite.port");
    String user = System.getProperty("com.mysql.fabric.testsuite.username");
    String password = System.getProperty("com.mysql.fabric.testsuite.password");
    String database = System.getProperty("com.mysql.fabric.testsuite.database");
    String fabricUsername = System.getProperty("com.mysql.fabric.testsuite.fabricUsername");
    String fabricPassword = System.getProperty("com.mysql.fabric.testsuite.fabricPassword");

    // Using JDBC Fabric connection to create database and table
    Class.forName("com.mysql.fabric.jdbc.FabricMySQLDriver");
    Connection con = DriverManager.getConnection("jdbc:mysql:fabric://" + hostname + ":" + Integer.valueOf(port)
            + "/mysql?fabricServerGroup=fabric_test1_global&fabricUsername=" + fabricUsername
            + "&fabricPassword=" + fabricPassword, user, password);
    Statement stmt = con.createStatement();
    stmt.executeUpdate("create database if not exists employees");
    con.close();//from  w ww.j  a v  a 2s  . c om

    con = DriverManager.getConnection("jdbc:mysql:fabric://" + hostname + ":" + Integer.valueOf(port) + "/"
            + database + "?fabricServerGroup=fabric_test1_global&fabricUsername=" + fabricUsername
            + "&fabricPassword=" + fabricPassword, user, password);
    stmt = con.createStatement();
    stmt.executeUpdate("create database if not exists employees");
    stmt.executeUpdate("drop table if exists employees.employees");
    stmt.executeUpdate(
            "create table employees.employees (emp_no INT PRIMARY KEY, first_name CHAR(40), last_name CHAR(40))");
    stmt.close();

    // we have to wait for replication ....
    Thread.sleep(2000);

    // Using Hibernate
    SessionFactory sf = createSessionFactory("http://" + hostname + ":" + port, user, password, fabricUsername,
            fabricPassword);

    // add some employees
    for (int i = 1; i < 11; ++i) {
        int j = i;
        // put a few in the other shard
        if ((j % 2) == 0) {
            j += 10000;
        }

        Session session = sf.withOptions().tenantIdentifier("" + j) // choose a db server
                .openSession();

        // vanilla hibernate code
        session.beginTransaction();
        Employee e = new Employee();
        e.setId(j);
        e.setFirstName("First name of employee " + j);
        e.setLastName("Smith" + j);
        session.save(e);

        session.getTransaction().commit();
        session.close();
    }

    // clean up
    con.createStatement().executeUpdate("drop table employees.employees");
    con.close();

}

From source file:org.springframework.orm.hibernate4.HibernateTransactionManagerTests.java

License:Apache License

@Test
public void testTransactionCommitWithEntityInterceptor() throws Exception {
    Interceptor entityInterceptor = mock(Interceptor.class);
    Connection con = mock(Connection.class);
    final SessionFactory sf = mock(SessionFactory.class);
    ImplementingSession session = mock(ImplementingSession.class);
    SessionBuilder options = mock(SessionBuilder.class);
    Transaction tx = mock(Transaction.class);

    given(sf.withOptions()).willReturn(options);
    given(options.interceptor(entityInterceptor)).willReturn(options);
    given(options.openSession()).willReturn(session);
    given(session.beginTransaction()).willReturn(tx);
    given(session.isOpen()).willReturn(true);
    given(session.isConnected()).willReturn(true);
    given(session.connection()).willReturn(con);

    HibernateTransactionManager tm = new HibernateTransactionManager(sf);
    tm.setEntityInterceptor(entityInterceptor);
    tm.setAllowResultAccessAfterCompletion(true);
    TransactionTemplate tt = new TransactionTemplate(tm);
    tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
    assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));
    assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());

    tt.execute(new TransactionCallbackWithoutResult() {
        @Override// ww w  .  jav  a2 s  .c o  m
        public void doInTransactionWithoutResult(TransactionStatus status) {
            assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf));
        }
    });

    assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));
    assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());

    verify(session).close();
    verify(tx).commit();
}

From source file:org.springframework.orm.hibernate4.HibernateTransactionManagerTests.java

License:Apache License

@Test
public void testTransactionCommitWithEntityInterceptorBeanName() throws Exception {
    Interceptor entityInterceptor = mock(Interceptor.class);
    Interceptor entityInterceptor2 = mock(Interceptor.class);
    Connection con = mock(Connection.class);
    final SessionFactory sf = mock(SessionFactory.class);
    ImplementingSession session = mock(ImplementingSession.class);
    SessionBuilder options = mock(SessionBuilder.class);
    Transaction tx = mock(Transaction.class);

    given(sf.withOptions()).willReturn(options);
    given(options.interceptor(entityInterceptor)).willReturn(options);
    given(options.interceptor(entityInterceptor2)).willReturn(options);
    given(options.openSession()).willReturn(session);
    given(session.beginTransaction()).willReturn(tx);
    given(session.isOpen()).willReturn(true);
    given(session.isConnected()).willReturn(true);
    given(session.connection()).willReturn(con);

    BeanFactory beanFactory = mock(BeanFactory.class);
    given(beanFactory.getBean("entityInterceptor", Interceptor.class)).willReturn(entityInterceptor,
            entityInterceptor2);/*from  www. ja  v a2  s  .  c om*/

    HibernateTransactionManager tm = new HibernateTransactionManager(sf);
    tm.setEntityInterceptorBeanName("entityInterceptor");
    tm.setBeanFactory(beanFactory);

    TransactionTemplate tt = new TransactionTemplate(tm);
    tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
    assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));
    assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());

    for (int i = 0; i < 2; i++) {
        tt.execute(new TransactionCallbackWithoutResult() {
            @Override
            public void doInTransactionWithoutResult(TransactionStatus status) {
                assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf));
            }
        });
    }

    assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));
    assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());

    verify(session, times(2)).close();
    verify(tx, times(2)).commit();
}