Do you know if I can get the arguments of the database from persistence.xml
, do you know if there is a source code that do it. Or should I parse persistence.xml
by myself?
I'm not aware of anything in the standard JPA API allowing to retrieve the driver class name, the jdbc url, the username and password.
Second problem, the keys for those properties are not standardized in JPA 1.0. For example, Hibernate will use:
<property name="hibernate.connection.driver_class" value=""/>
<property name="hibernate.connection.url" value=""/>
<property name="hibernate.connection.username" value=""/>
<property name="hibernate.connection.password" value=""/>
While EclipseLink will use:
<property name="eclipselink.jdbc.driver" value=""/>
<property name="eclipselink.jdbc.url" value=""/>
<property name="eclipselink.jdbc.user" value=""/>
<property name="eclipselink.jdbc.password" value=""/>
This may make the parsing fragile.
If this is an option, maybe you could use a properties file to store both the provider specific keys and the values (I'd recommend using the standardized JPA 2.0 properties as keys). For example:
# keys for JPA
javax.persistence.jdbc.driver = hibernate.connection.driver_class
javax.persistence.jdbc.url = hibernate.connection.url
javax.persistence.jdbc.user = hibernate.connection.username
javax.persistence.jdbc.password = hibernate.connection.password
# values common to JPA and JDBC
driver = org.h2.Driver
url = jdbc:h2:mem:test
username = scott
password = tiger
And use Persistence.createEntityManagerFactory(String, Map)
and pass a Map
that you'll feed with the properties from the file to create the EntityManagerFactory
:
Map map = new HashMap();
map.put(...);
...
EntityManagerFactory emf = Persistence.createEntityManagerFactory("MyPu", map);