How to get Hibernate configuration properties?
Asked Answered
F

2

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.

Fruge answered 17/11, 2009 at 13:37 Comment(0)
G
5

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.

Gregorygregrory answered 17/11, 2009 at 14:19 Comment(2)
sessionFactory cannot be resolved to a variable. How can I get one? I searched thru SessionFactory* classes to get an instance but I have no idea what I'm doing. All I have at hand is a javax.persistance.EntityManagerSaintmihiel
I have not used EntityManager, but it looks like the Hibernate implementation of that is HibernateEntityManager, which has a getSession method. Once you have the session, you can get the SessionFactory. So something like ((HibernateEntityManager)entityManager).getSession().getSessionFactory()Gregorygregrory
B
3

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?

Bigamous answered 17/11, 2009 at 14:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.