我正在使用Hibernate 3.x和Jboss。 目前我们支持多个数据库。如何从休眠提供程序知道底层数据库名称
现在在运行时,我怎么能知道底层的数据库信息?至少是名字还是数据库方言? (例如MySQL,Derby,Oracle等)?
任何人都可以建议任何方式来找到这些信息? 我以为hibernate的SessionFactory类会提供这样的API - 但它不是?
由于提前,
我正在使用Hibernate 3.x和Jboss。 目前我们支持多个数据库。如何从休眠提供程序知道底层数据库名称
现在在运行时,我怎么能知道底层的数据库信息?至少是名字还是数据库方言? (例如MySQL,Derby,Oracle等)?
任何人都可以建议任何方式来找到这些信息? 我以为hibernate的SessionFactory类会提供这样的API - 但它不是?
由于提前,
既然你有一张hibernate.properties或hibernate.cfg.xml文件中,你可以阅读永诺关闭这些文件的任何信息。
我认为你可以这样来做:
sessionFactory.getCurrentSession().connection().getMetaData().getURL()
请注意,此方法会在不关闭的情况下创建一个废弃的连接。 – DanielK 2016-09-27 12:31:47
非常感谢javamonkey79和斯特凡诺为应对这一问题。
是的 - 我可以读取hibernate.properties/cfg.xml文件 - 但我想避免文件读取工作流程。
看来Session::connection()
api现在已被弃用,但它仍然有效。 我们也可以用下面列出的其他方法检索相同的信息。
Session session = sessionFactory.openSession();
String dbURL = session.connection().getMetaData().getURL().toString();
session.close();
Settings settings = ((SessionFactoryImpl) sessionFactory).getSettings();
if (settings != null) {
Connection connection = settings.getConnectionProvider().getConnection();
String dbURL = connection.getMetaData().getURL();
connection.close();
}
对于MySQL,返回URL将在形式:
jdbc:mysql://localhost:3306/edm?useUnicode=true
sessionFactory.getDialect();
给你Dialect
和
sessionFactory.getSettings().getConnectionProvider().getConnection().getMetaData().getURL();
为您提供连接网址。
注意:这只与SessionFactoryImpl
类的工作,不与接口
或者你可以尝试:
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
SessionFactoryImpl sessionFactoryImpl = (SessionFactoryImpl) sessionFactory;
Properties props = sessionFactoryImpl.getProperties();
String url = props.get("hibernate.connection.url").toString();
String[] urlArray = url.split(":");
String db_name = urlArray[urlArray.length - 1];
我希望这将是我可以看到所有Hibernate属性的一种方式,但它似乎只在从文件hibernate.cfg.xml中读取配置时才起作用。我使用Spring来配置Hibernate,因此它不起作用。任何想法如何访问由Spring创建的SessionFactoryImpl? – 2015-04-12 04:21:21
,你可以试试这个代码:
String url = null;
try {
url = getSession().connection().getMetaData().getURL().toString();
} catch (HibernateException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
String[] urlArray = url.split(":");
String db_name = urlArray[1];
;)
可能的重复:http://stackoverflow.co m/questions/821466/how-can-i-get-the-database-name -i-am-connected-through-hibernate – javamonkey79 2010-12-04 01:55:39