0

I work with JPA2 and I use a multiple persistence unit configuration that is represented in my persistence.xml, like this:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0">                           
  <persistence-unit name="FirstPU" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <class>entities.Book</class>
    <properties>        
      <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
      ...
    </properties>
  </persistence-unit>  
  <persistence-unit name="SecondPU" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <class>entities.Book</class>
    <properties>        
      <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
      ...
    </properties>
  </persistence-unit>  
</persistence>

Is there any method to extract persistence unit names from persistence.xml programmatically (using Hibernate or JPA2)? Like this:

EntityManagerFactory emf = Persistence.createEntityManagerFactory("manager1");

// or

Map<String, Object> configOverrides = new HashMap<String, Object>();
configOverrides.put("hibernate.hbm2ddl.auto", "create-drop");
EntityManagerFactory programmaticEmf =
    Persistence.createEntityManagerFactory("manager1", configOverrides);

But I need to read not only properties.

Daniel Serodio
  • 4,229
  • 5
  • 37
  • 33
ilya8891
  • 127
  • 1
  • 1
  • 12
  • You can refer to [http://stackoverflow.com/questions/5393167/get-the-persistence-unit-name] question – Shailendra Sep 18 '12 at 13:00
  • I don't have an initialized EntiyManagerFactory or an opened EntityManager. I need to select a persistence unit from the list in the persistence.xml before some initializations will be fulfilled. Moreover the link is about connection method that is deprecated. – ilya8891 Sep 19 '12 at 05:13
  • 1
    If I am understanding you right then just simply parse the persistence.xml file using any of number of available java xml parsers and get the name attribute of all persistence-unit elements. And of course you know the path of the persistence xml, its META-INF/persitence.xml. Infact Hibernate itself uses a SAX parser to read variety of configuration files. – Shailendra Sep 19 '12 at 05:47
  • Yes, I think so too. Or other decision is to store some available names of persistence unit programmatically (within a final static array or array list, for example) and to create EntityManagerFactory dynamically ([link](http://www.datanucleus.org/products/accessplatform_3_0/jpa/persistence_unit.html)). Thanks. – ilya8891 Sep 19 '12 at 05:55

0 Answers0