Java Code Examples for org.hibernate.Session#connection()

The following examples show how to use org.hibernate.Session#connection() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
public static Connection getConnection(Session session) {
		// Hibernate 3
		return session.connection();
		
		// following code for Hibernate 4
//		try {
//			// reflective lookup to bridge between Hibernate 3.x and 4.x
//			// see http://stackoverflow.com/questions/3526556/session-connection-deprecated-on-hibernate
//			Method connectionMethod = session.getClass().getMethod(
//						"connection");
//			return (Connection) connectionMethod.invoke(session);
//		} catch (NoSuchMethodException e) {
//			throw new IllegalStateException(
//					"Cannot find connection() method on Hibernate session", e);
//		} catch (IllegalArgumentException e) {
//			throw new IllegalStateException(
//					"IllegalArgumentException invoking connection() method on Hibernate session", e);
//		} catch (IllegalAccessException e) {
//			throw new IllegalStateException(
//					"IllegalAccessException invoking connection() method on Hibernate session", e);
//		} catch (InvocationTargetException e) {
//			throw new IllegalStateException(
//					"InvocationTargetException invoking connection() method on Hibernate session", e);
//		}
	}
 
Example 2
@Override
protected void tearDown() throws Exception {
    Session session = null;
    Connection c = null;
    Statement stmt = null;
    try {
        session = HibernateFactory.getSession();
        c = session.connection();
        stmt = c.createStatement();
        forceQuery(c, "drop table adv_datasource");
        c.commit();
    }
    finally {
        HibernateHelper.cleanupDB(stmt);
    }
}
 
Example 3
Source Project: spacewalk   File: RamTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void verifyInDb(Long serverId, long ram, long swap)
       throws Exception {
       // Now lets manually test to see if the user got updated
       Session session = null;
       Connection c = null;
       ResultSet rs = null;
       PreparedStatement ps = null;
       try {
           session = HibernateFactory.getSession();
           c = session.connection();
           assertNotNull(c);
           ps = c.prepareStatement(
               "SELECT ID, RAM, SWAP FROM RHNRAM " +
"  WHERE SERVER_ID = " + serverId);
           rs = ps.executeQuery();
           rs.next();

           assertEquals(ram, rs.getLong("RAM"));
           assertEquals(swap, rs.getLong("SWAP"));
       }
       finally {
           rs.close();
           ps.close();
       }
   }
 
Example 4
protected static void oneTimeTeardown() throws Exception {

        Connection c = null;
        Statement stmt = null;
        Session session = null;
        try {
            session = HibernateFactory.getSession();
            c = session.connection();
            stmt = c.createStatement();
            // Couldn't select 1, so the table didn't exist, create it
            forceQuery(c, "drop sequence persist_sequence");
            forceQuery(c, "drop table persist_test");
        }
        finally {
            HibernateHelper.cleanupDB(stmt);
        }
    }
 
Example 5
public void testRawInsert() throws Exception {
    final Session session = HibernateUtil.getSession();
    try {
        final Connection connection = session.connection();
        final Statement statement = connection.createStatement();
        try {
            statement.executeUpdate("insert into o_stat_daily (businesspath,resid,day,value) values ('businesspath',101,now(),202)");
            connection.commit();
        } finally {
            statement.close();
        }
    } finally {
        session.close();
    }

}
 
Example 6
public void testRawInsert() throws Exception {
    final Session session = HibernateUtil.getSession();
    try {
        final Connection connection = session.connection();
        final Statement statement = connection.createStatement();
        try {
            statement.executeUpdate("insert into o_stat_hourofday (businesspath,resid,hour,value) values ('businesspath',101,2,202)");
            connection.commit();
        } finally {
            statement.close();
        }
    } finally {
        session.close();
    }

}
 
Example 7
public void testRawInsert() throws Exception {
    final Session session = HibernateUtil.getSession();
    try {
        final Connection connection = session.connection();
        final Statement statement = connection.createStatement();
        try {
            statement.executeUpdate("insert into o_stat_dayofweek (businesspath,resid,day,value) values ('businesspath',101,2,202)");
            connection.commit();
        } finally {
            statement.close();
        }
    } finally {
        session.close();
    }

}
 
Example 8
public void testRawInsert() throws Exception {
    final Session session = HibernateUtil.getSession();
    try {
        final Connection connection = session.connection();
        final Statement statement = connection.createStatement();
        try {
            statement.executeUpdate("insert into o_stat_daily (businesspath,resid,day,value) values ('businesspath',101,now(),202)");
            connection.commit();
        } finally {
            statement.close();
        }
    } finally {
        session.close();
    }

}
 
Example 9
public void testRawInsert() throws Exception {
    final Session session = HibernateUtil.getSession();
    try {
        final Connection connection = session.connection();
        final Statement statement = connection.createStatement();
        try {
            statement.executeUpdate("insert into o_stat_hourofday (businesspath,resid,hour,value) values ('businesspath',101,2,202)");
            connection.commit();
        } finally {
            statement.close();
        }
    } finally {
        session.close();
    }

}
 
Example 10
public void testSchemaTools() throws Exception{
	// database schema have been created thanks to the setUp method
	// we have 2 schemas SA et SB, SB must be set as the default schema
	// used by hibernate hibernate.default_schema SB
	SchemaExport se = new SchemaExport(getCfg());
	se.create(true,true);
	
	// here we modify the generated table in order to test SchemaUpdate
	Session session = openSession();
	Connection conn = session.connection();
	Statement stat = conn.createStatement();
	stat.execute("ALTER TABLE \"SB\".\"Team\" DROP COLUMN name ");
	
	// update schema
	SchemaUpdate su = new SchemaUpdate(getCfg());
	su.execute(true,true);
	
	// we can run schema validation. Note that in the setUp method a *wrong* table
	// has been created with different column names
	// if schema validator chooses the bad db schema, then the testcase will fail (exception)
	SchemaValidator sv = new SchemaValidator(getCfg());
	sv.validate();
	
	// it's time to clean our database
	se.drop(true,true);
	
	// then the schemas and false table.

	stat.execute("DROP TABLE \"SA\".\"Team\" ");
	stat.execute(" DROP SCHEMA sa ");
	stat.execute("DROP SCHEMA sb ");
	stat.close();
	session.close();
}
 
Example 11
public void testSchemaToolsNonQuote() throws Exception{
	// database schema have been created thanks to the setUp method
	// we have 2 schemas SA et SB, SB must be set as the default schema
	// used by hibernate hibernate.default_schema SB
	SchemaExport se = new SchemaExport(getCfg());
	se.create(true,true);
	
	// here we modify the generated table in order to test SchemaUpdate
	Session session = openSession();
	Connection conn = session.connection();
	Statement stat = conn.createStatement();
	stat.execute("ALTER TABLE \"SB\".\"TEAM\" DROP COLUMN xname ");
	
	// update schema
	SchemaUpdate su = new SchemaUpdate(getCfg());
	su.execute(true,true);
	
	// we can run schema validation. Note that in the setUp method a *wrong* table
	// has been created with different column names
	// if schema validator chooses the bad db schema, then the testcase will fail (exception)
	SchemaValidator sv = new SchemaValidator(getCfg());
	sv.validate();
	
	// it's time to clean our database
	se.drop(true,true);
	
	// then the schemas and false table.

	stat.execute("DROP TABLE \"SA\".\"Team\" ");
	stat.execute(" DROP SCHEMA sa ");
	stat.execute("DROP SCHEMA sb ");
	stat.close();
	session.close();
}
 
Example 12
public void testBorrowedConnections() throws Throwable {
	prepare();
	Session s = getSessionUnderTest();

	Connection conn = s.connection();
	assertTrue( ( ( SessionImpl ) s ).getJDBCContext().getConnectionManager().hasBorrowedConnection() );
	conn.close();
	assertFalse( ( ( SessionImpl ) s ).getJDBCContext().getConnectionManager().hasBorrowedConnection() );

	release( s );
	done();
}
 
Example 13
Source Project: spacewalk   File: DmiTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void verifyInDb(Long id, Map params) throws Exception {
    // Now lets manually test to see if the user got updated
    Session session = null;
    Connection c = null;
    ResultSet rs = null;
    PreparedStatement ps = null;
    try {
        session = HibernateFactory.getSession();
        c = session.connection();
        assertNotNull(c);
        ps = c.prepareStatement(
            "SELECT * FROM RHNSERVERDMI " +
            "  WHERE ID = " + id);
        rs = ps.executeQuery();
        rs.next();

        assertEquals(id.longValue(), rs.getLong("ID"));
        assertEquals(params.get("vendor"), rs.getString("VENDOR"));
        assertEquals(params.get("system"), rs.getString("SYSTEM"));
        assertEquals(params.get("product"), rs.getString("PRODUCT"));
        assertEquals(params.get("biosvendor"), rs.getString("BIOS_VENDOR"));
        assertEquals(params.get("biosversion"), rs.getString("BIOS_VERSION"));
        assertEquals(params.get("biosrelease"), rs.getString("BIOS_RELEASE"));
        assertEquals(params.get("asset"), rs.getString("ASSET"));
        assertEquals(params.get("board"), rs.getString("BOARD"));
    }
    finally {
        rs.close();
        ps.close();
    }
}
 
Example 14
public void testDeleteNeededErrataCache() throws Exception {
    // create a lot of stuff to test this simple insert.
    Long oid = UserTestUtils.createOrg("testOrg" + this.getClass().getSimpleName());
    User user = UserTestUtils.createUser("testUser", oid);
    Server server = ServerFactoryTest.createTestServer(user);
    Errata e = ErrataFactoryTest.createTestErrata(oid);
    Long sid = server.getId();
    Long eid = e.getId();

    Package p = e.getPackages().iterator().next();

    // insert record into table
    int rows = ErrataCacheManager.insertNeededErrataCache(sid, eid, p.getId());
    assertEquals(1, rows);

    // verify what was inserted
    Session session = HibernateFactory.getSession();
    Connection conn = session.connection();
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery(
            "select * from rhnServerNeededErrataCache where server_id = " +
            sid.toString());
    assertTrue(rs.next());
    assertEquals(sid.longValue(), rs.getLong("server_id"));
    assertEquals(eid.longValue(), rs.getLong("errata_id"));

    // make sure we don't have more
    assertFalse(rs.next());

    // now let's delete the above record
    rows = ErrataCacheManager.deleteNeededErrataCache(sid, eid);
    assertEquals(1, rows);

    rs = stmt.executeQuery(
            "select * from rhnServerNeededErrataCache where server_id = " +
            sid.toString());
    assertFalse(rs.next());
}
 
Example 15
private void verifyInDb(Long id, String value) throws Exception {
    // Now lets manually test to see if the user got updated
    Session session = null;
    Connection c = null;
    ResultSet rs = null;
    PreparedStatement ps = null;
    String rawValue = null;
    try {
        session = HibernateFactory.getSession();
        c = session.connection();
        assertNotNull(c);
        ps = c.prepareStatement(
            "SELECT PROP1 FROM RHNDEVICE " +
            "  WHERE ID = " + id);
        rs = ps.executeQuery();
        rs.next();
        rawValue = rs.getString("PROP1");
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    finally {
        rs.close();
        ps.close();
    }

    assertNotNull(rawValue);
    assertEquals(value, rawValue);
}
 
Example 16
@Override
protected void doCleanupAfterCompletion(Object transaction) {
	HibernateTransactionObject txObject = (HibernateTransactionObject) transaction;

	// Remove the session holder from the thread.
	if (txObject.isNewSessionHolder()) {
		TransactionSynchronizationManager.unbindResource(getSessionFactory());
	}

	// Remove the JDBC connection holder from the thread, if exposed.
	if (getDataSource() != null) {
		TransactionSynchronizationManager.unbindResource(getDataSource());
	}

	Session session = txObject.getSessionHolder().getSession();
	if (this.prepareConnection && session.isConnected() && isSameConnectionForEntireSession(session)) {
		// We're running with connection release mode "on_close": We're able to reset
		// the isolation level and/or read-only flag of the JDBC Connection here.
		// Else, we need to rely on the connection pool to perform proper cleanup.
		try {
			Connection con = session.connection();
			DataSourceUtils.resetConnectionAfterTransaction(con, txObject.getPreviousIsolationLevel());
		}
		catch (HibernateException ex) {
			logger.debug("Could not access JDBC Connection of Hibernate Session", ex);
		}
	}

	if (txObject.isNewSession()) {
		if (logger.isDebugEnabled()) {
			logger.debug("Closing Hibernate Session [" + SessionFactoryUtils.toString(session) +
					"] after transaction");
		}
		SessionFactoryUtils.closeSessionOrRegisterDeferredClose(session, getSessionFactory());
	}
	else {
		if (logger.isDebugEnabled()) {
			logger.debug("Not closing pre-bound Hibernate Session [" +
					SessionFactoryUtils.toString(session) + "] after transaction");
		}
		if (txObject.getSessionHolder().getPreviousFlushMode() != null) {
			session.setFlushMode(txObject.getSessionHolder().getPreviousFlushMode());
		}
		if (!this.hibernateManagedSession) {
			session.disconnect();
		}
	}
	txObject.getSessionHolder().clear();
}
 
Example 17
@Override
@SuppressWarnings("deprecation")
protected void doCleanupAfterCompletion(Object transaction) {
	HibernateTransactionObject txObject = (HibernateTransactionObject) transaction;

	// Remove the session holder from the thread.
	if (txObject.isNewSessionHolder()) {
		TransactionSynchronizationManager.unbindResource(getSessionFactory());
	}

	// Remove the JDBC connection holder from the thread, if exposed.
	if (getDataSource() != null) {
		TransactionSynchronizationManager.unbindResource(getDataSource());
	}

	Session session = txObject.getSessionHolder().getSession();
	if (this.prepareConnection && session.isConnected() && isSameConnectionForEntireSession(session)) {
		// We're running with connection release mode "on_close": We're able to reset
		// the isolation level and/or read-only flag of the JDBC Connection here.
		// Else, we need to rely on the connection pool to perform proper cleanup.
		try {
			Connection con = session.connection();
			DataSourceUtils.resetConnectionAfterTransaction(con, txObject.getPreviousIsolationLevel());
		}
		catch (HibernateException ex) {
			logger.debug("Could not access JDBC Connection of Hibernate Session", ex);
		}
	}

	if (txObject.isNewSession()) {
		if (logger.isDebugEnabled()) {
			logger.debug("Closing Hibernate Session [" + SessionFactoryUtils.toString(session) +
					"] after transaction");
		}
		SessionFactoryUtils.closeSessionOrRegisterDeferredClose(session, getSessionFactory());
	}
	else {
		if (logger.isDebugEnabled()) {
			logger.debug("Not closing pre-bound Hibernate Session [" +
					SessionFactoryUtils.toString(session) + "] after transaction");
		}
		if (txObject.getSessionHolder().getPreviousFlushMode() != null) {
			session.setFlushMode(txObject.getSessionHolder().getPreviousFlushMode());
		}
		if (!this.hibernateManagedSession) {
			session.disconnect();
		}
	}
	txObject.getSessionHolder().clear();
}
 
Example 18
/** Execute the task
 *  @throws IOException If the output file can't be opened.
 *  @throws SQLException if something goes wrong with the DB.
 */
public void execute() throws IOException, SQLException {
    Session session = null;
    Connection conn = null;
    try {
        session = HibernateFactory.getSession();
        conn = session.connection();
        PrintStream out = new PrintStream(new FileOutputStream(outfile));

        Collection fileKeys = ModeFactory.getKeys();

        TreeSet ts = new TreeSet(fileKeys);
        Iterator i = ts.iterator();
        while (i.hasNext()) {
            String file = (String)i.next();
            Map queries = ModeFactory.getFileKeys(file);
            if (file.equals("test_queries")) {
                continue;
            }
            out.println("\nFile:   " + file);

            Iterator q = new TreeSet(queries.keySet()).iterator();
            int count = 0;
            while (q.hasNext()) {
                Mode m = (Mode)queries.get(q.next());

                /* Don't do plans for queries that use system tables or for
                 * dummy queries.
                 */
                if (shouldSkip(m)) {
                    out.println("\nSkipping dummy query:  " + m.getName());
                    continue;
                }
                if (!(m instanceof SelectMode)) {
                    out.println("\nSkipping Write or Callable mode: " + m.getName());
                    continue;
                }
                out.println("\nPlan for " + m.getName());

                String query = "EXPLAIN PLAN " +
                    "SET STATEMENT_ID='" + QUERY_NAME + "' FOR " +
                    m.getQuery().getOrigQuery();

                // HACK!  Some of the queries actually have %s in them.
                // So, replace all %s with :rbb so that the explain plan
                // can be generated.
                query = query.replaceAll("%s", ":rbb");

                PreparedStatement ps = conn.prepareStatement(query);

                ps.execute();
                ps.close();

                // Now that we have generated the explain plan, we just
                // need to get it from the DB.
                ps = conn.prepareStatement(EXPLAIN_QUERY);
                ps.setString(1, QUERY_NAME);
                ps.setString(2, QUERY_NAME);
                ResultSet rs = ps.executeQuery();
                while (rs.next()) {
                    String parentId = rs.getString("explain_parent_id");
                    String id = rs.getString("explain_id");
                    String operation = rs.getString("explain_operation");

                    out.println(parentId + " " + id + " " + operation);
                }
                count++;
                rs.close();
                ps.close();
                Statement st = conn.createStatement();
                st.execute("Delete FROM plan_table where " +
                                "STATEMENT_ID='" + QUERY_NAME + "'");
                st.close();

            }
        }
        out.close();
    }
    catch (HibernateException he) {
        throw new
            HibernateRuntimeException(
                "HibernateException in ExplainPlanGenerator.", he);
    }
}
 
Example 19
public void testDeleteNeededPackageCache() throws Exception {
    // create a lot of stuff to test this simple insert.
    Long oid = UserTestUtils.createOrg("testOrg" + this.getClass().getSimpleName());
    Org org = OrgFactory.lookupById(oid);
    User user = UserTestUtils.createUser("testUser", oid);
    Server server = ServerFactoryTest.createTestServer(user);
    Package pkg = PackageTest.createTestPackage(org);
    Errata e = ErrataFactoryTest.createTestErrata(oid);
    Long sid = server.getId();
    Long eid = e.getId();
    Long pid = pkg.getId();

    // insert record into table
    int rows = ErrataCacheManager.insertNeededErrataCache(
            sid, eid, pid);
    assertEquals(1, rows);

    // verify what was inserted
    Session session = HibernateFactory.getSession();
    Connection conn = session.connection();
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery(
            "select * from rhnServerNeededPackageCache where server_id = " +
            sid.toString());
    assertTrue(rs.next());
    assertEquals(sid.longValue(), rs.getLong("server_id"));
    assertEquals(eid.longValue(), rs.getLong("errata_id"));
    assertEquals(pid.longValue(), rs.getLong("package_id"));

    // make sure we don't have more
    assertFalse(rs.next());

    // now let's delete the above record
    rows = ErrataCacheManager.deleteNeededPackageCache(sid, eid, pid);
    assertEquals(1, rows);

    rs = stmt.executeQuery(
            "select * from rhnServerNeededPackageCache where server_id = " +
            sid.toString());
    assertFalse(rs.next());
}
 
Example 20
public void testIntegrityViolation() throws Exception {
	if ( getDialect() instanceof MySQLMyISAMDialect ) {
		reportSkip( "MySQL (ISAM) does not support FK violation checking", "exception conversion" );
		return;
	}
	
	SQLExceptionConverter converter = getDialect().buildSQLExceptionConverter();

	Session session = openSession();
	session.beginTransaction();
	Connection connection = session.connection();

	// Attempt to insert some bad values into the T_MEMBERSHIP table that should
	// result in a constraint violation
	PreparedStatement ps = null;
	try {
		ps = connection.prepareStatement("INSERT INTO T_MEMBERSHIP (user_id, group_id) VALUES (?, ?)");
		ps.setLong(1, 52134241);    // Non-existent user_id
		ps.setLong(2, 5342);        // Non-existent group_id
		ps.executeUpdate();

		fail("INSERT should have failed");
	}
	catch(SQLException sqle) {
		JDBCExceptionReporter.logExceptions(sqle, "Just output!!!!");
		JDBCException jdbcException = converter.convert(sqle, null, null);
		assertEquals( "Bad conversion [" + sqle.getMessage() + "]", ConstraintViolationException.class , jdbcException.getClass() );
		ConstraintViolationException ex = (ConstraintViolationException) jdbcException;
		System.out.println("Violated constraint name: " + ex.getConstraintName());
	}
	finally {
		if ( ps != null ) {
			try {
				ps.close();
			}
			catch( Throwable ignore ) {
				// ignore...
			}
		}
	}

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