How can I get the name of the database I'm connected to through Hibernate?

I am trying to get the name of the database I'm connected to in SQL Server. I tried:

Query query = session.createQuery("SELECT db_name()"); List<String> dbNames = query.list(); 

However, I got the following error:

 [ERROR PARSER:35] *** ERROR: <AST>:0:0: unexpected end of subtree Exception in thread "main" java.lang.IllegalStateException: No data type for node: org.hibernate.hql.ast.MethodNode \-[METHOD_CALL] MethodNode: '(' +-[METHOD_NAME] IdentNode: 'db_name' {originalText=db_name} \-[EXPR_LIST] SqlNode: 'exprList' 

How can I get the name of the database I'm connected to?

+2
java sql-server hibernate
source share
2 answers

You can:

  • Create your own SQL query with session.createSQLQuery(...) . You can extract a single row of results using uniqueResult() .

  • Get JDBC Connection from Session and retrieve the connection string from the database metadata. For SQL Server, I believe that you need to parse connection.getMetaData().getURL() to retrieve the actual database name.

Please note that Session.connection() is deprecated and you should use Session.doWork() .

+6
source share

AFAIK, you cannot call NAtive database functions this way. Try using your own query instead of a simple query: http://www.roseindia.net/hibernate/hibernate-native-sql.shtml

+1
source share

Source: https://habr.com/ru/post/649823/


All Articles