views:

168

answers:

2

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  A: 

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?

Peter D
+1  A: 

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.

Brian Deterling