How do I determine the DataSource being used by a Hibernate Session?

hibernate, hsqldb, java, junit

Solution

Regardless of wrappers and concrete implementation of Hibernate/Spring and so on, you may check not DataSource, but database type (and this might be suitable).

The idea is in the usage of DatabaseMetaData and check type against it (as Hibernate detects dialect):

private boolean isTestDb(Session session) {
    return session.doReturningWork(new ReturningWork<Boolean>() {
        @Override
        public Boolean execute(Connection connection) throws SQLException {
            DatabaseMetaData metaData = connection.getMetaData();
            return metaData.getDatabaseProductName().startsWith("HSQL");
        }
    });
}

Note, that body of method can be changed in the way you want (check JDBC URL, check driver name, check almost anything).

Edit: approach above is working for hibernate 3.5+.

For Hibernate earlier version(e.g. 3.2) it might be even easier:

private boolean isTestDb(Session session) {
    Conection connection = session.connection();//deprecated method, which was dumped in hibernate 3.5+
    DatabaseMetaData metaData = connection.getMetaData();
    return metaData.getDatabaseProductName().startsWith("HSQL");
}

Problem

I have several unit tests that should be using a HSQLDB but I know some of them are actually hitting a physical DB. I want to add a check to the test to make sure that the DataSource being used is for HSQLDB and not the live DB. From a hibernate session object (`org.hibernate.classic.Session`), How do I check the DataSource Update: I also have access to the session factory (`org.hibernate.impl.SessionFactory`). Details: Hibernate 3.2

Original source