Search code examples
jpaeclipselinkpersistence.xml

Dynamically add managed class names to EntityManagerFactory


Say I have a persistence.xml file like this:

<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
  <persistence-unit name="pu" transaction-type="RESOURCE_LOCAL">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <class>entity.E1</class>
    <class>entity.E2</class>
    <class>entity.E3</class>
    <exclude-unlisted-classes>false</exclude-unlisted-classes>
    <properties>
      <property name="javax.persistence.jdbc.url" value="jdbc:derby:memory:myTestDB;create=true"/>
      <property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeddedDriver"/>
      <property name="eclipselink.logging.level" value="WARNING"/>
      <property name="eclipselink.canonicalmodel.subpackage" value="test"/>
      <property name="javax.persistence.schema-generation.database.action" value="create"/>
    </properties>
  </persistence-unit>
</persistence>

I know I can change the persistence.xml file from code like this, but only the properties section:

Properties properties = new Properties();
properties.put("javax.persistence.jdbc.url", "<value>");
properties.put("eclipselink.logging.level", "<value>");
....
emf = Persistence.createEntityManagerFactory("pu", properties);

I can get all the Entity classes via reflection, but how can I add the class names (E1..E3 in the example) dynamically in a way similar to what I did for the properties?

I know Hibernate has a way to do it, but I'm using eclipselink. Is there a way to do it with eclipselinks JPA-implementation?


Solution

  • I originally spent a lot of time on this problem/question and have given up on my original idea (dynamically add entity classes). So if you read this question, my own answer is, I'm pretty sure it can't be done.