Java – how to determine the datasource being used by a hibernate session?
I have several unit tests that should use HSQLDB, but I know some of them are actually using physical databases I want to add a check to the test to ensure that the datasource being used is used for HSQLDB, not real-time dB
From the hibernate session object (org. Hibernate. Classic. Session), how do I check the datasource
Update: I can also visit the session factory (org. Hibernate. Impl. Sessionfactory)
Details: Hibernate 3.2
Solution
Regardless of the wrapper and implementation of Hibernate / spring, etc., you can check not the datasource, but the database type (which may be appropriate)
The idea is to use databasemetadata and check its type (because hibernate detects dialects):
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 you can change the method body the way you want (check the JDBC URL, check the driver name, check almost everything)
Edit: the above method is applicable to hibernate 3.5
For earlier versions of Hibernate (such as 3.2), it may be easier to:
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"); }