Reputation: 33
Is there a way to get some information of the underlying database version through the Hibernate 3.2 API? I failed to find relevant bits both here and the javadoc.
Upvotes: 3
Views: 2622
Reputation: 1072
Possible with some unwraps:
Session hibSession = ... // session is taken from wherever is possible
String dbVersion = hibSession.unwrap(SharedSessionContractImplementor.class)
.getJdbcCoordinator()
.getLogicalConnection()
.getPhysicalConnection()
.getMetadata()
.getDatabaseProductVersion();
There are also separate methods for major/minor versions available, as well as JDBC protocol version, DB vendor name etc.
Upvotes: 0
Reputation: 1209
An easier approach than the accepted answer is to use the java.sql.DatabaseMetaData class:
try (Session session = sessionFactory.openSession()) {
session.doWork(connection -> {
DatabaseMetaData metaData = connection.getMetaData();
System.out.println("Product version: " + metaData.getDatabaseProductVersion());
System.out.println("Major version: " + metaData.getDatabaseMajorVersion());
System.out.println("Minor version: " + metaData.getDatabaseMinorVersion());
});
}
For my MySQL 5.5 instance, this outputs:
Product version: 5.5.62-log
Major version: 5
Minor version: 5
The Product version is identical to the value returned by SELECT VERSION();
Upvotes: 0
Reputation: 7202
public static void testConnection() {
Session session = null;
try {
session = getSessionFactory().openSession();
session.doWork(connection -> {
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT VERSION()");
resultSet.next();
System.out.println("DB test: " + resultSet.getString(1));
});
} finally {
if (session != null && session.isOpen()) {
session.close();
}
}
}
Upvotes: 0
Reputation: 81489
Getting the version of your database engine is implementation specific. This means that there's no shared method for getting the version and so Hibernate cannot really provide an API since it is not bound to any particular RDBMS. For example, here are some different ways you get the version with SELECT statements from some well-known RDBMSs:
You could create a view that reports the version and then add that to your ORM which would then be accessible as any other Hibernate object.
Upvotes: 2