I have this requirement to add entity classes to the persistence unit at runtime rather than specifying all of them in the persistence.xml. Can someone help me with the same
JPA doesn't offer this feature yet. Here are three options you can check out :
Programmatically loading Entity classes with JPA 2.0?
This question on SO is similar to yours. An answer reports that it feasible with Spring.
JPA 2.0: Adding entity classes to PersistenceUnit *from different jar* automatically
Good pointers are given here.
Last but not least, a simple work around :
1. Generate a persistence.xml on the fly (simple XML file creation) with a new persistence unit.
2. Add persistence file to classpath dynamically (URLCLassLoader)
3. Ask PersistenceProvider to load new persistence unit (createEntityManagerFactory)
EDIT:
If the JPA provider is Hibernate, since Hibernate 4.0, it's possible to pass directly entities to this JPA provider without declaring them in the persistence.xml file. Hibernate will handle the entities on the fly.
EDIT:
Here is a sample configuration of JPA 2.1 + Hibernate 4.3.7.Final without declaring any entities :
META-INF/persistence.xml
org.hibernate.jpa.HibernatePersistenceProvider
References