开发者

How to get database version through Hibernate?

Is there a way to get some information of the underlying dat开发者_运维问答abase version through the Hibernate 3.2 API? I failed to find relevant bits both here and the javadoc.


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:

  • Oracle: SELECT * FROM v$version;
  • SQL Server: SELECT @@version
  • MySQL: SELECT VERSION()
  • ...

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.


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();
        }
    }

}


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();


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜