How to get Hibernate configuration properties?

前端 未结 2 417
孤街浪徒
孤街浪徒 2021-01-15 15:07

I`m using hibernate with jpa, and it is configured with persistence.xml Is it possible to get hibernate connection properties from web application?

Thanks.

相关标签:
2条回答
  • 2021-01-15 15:37

    Probably not without using reflection and relying on the Hibernate not to break your code in the future. You need to get the properties from the SessionFactory but it's not public so you would have to find the Field via reflection, then use field.setAccessibleto get access to it. Something like:

    Field f = SessionFactoryImpl.class.getDeclaredField("properties");
    f.setAccessible(true);
    Properties p = (Properties)f.get(sessionFactory);
    

    Then use the constants in Environment to pull out the relevant settings. If you're looking for the actual database connection settings and your app is using jndi, then it's possible you can use the jndi name to get a DataSource and examine that to get connection information.

    For this type of thing I usually just use the debugger, set a breakpoint, and then poke around the variables until I find where the information is; then see if it's publicly available and if not, use reflection to get to it. There are no guarantees though.

    0 讨论(0)
  • 2021-01-15 15:52

    If you are using JDBC you can always get a connection and its metadata. If you are using a Spring transaction manager you could get it like this:

    transactionManager.getDataSource().getConnection().getMetaData()
    

    This shows tons of information about your database and its connection including the username. There is some information in the persistence.xml that might deal with database connection pooling which usually isn't stored anywhere in Hibernate but in the actually connection pooling code.

    What information do you need to get from the persistence.xml file?

    0 讨论(0)
提交回复
热议问题