Adding entity classes dynamically at runtime

前端 未结 2 1472
梦谈多话
梦谈多话 2020-12-02 09:48

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

2条回答
  •  无人及你
    2020-12-02 10:31

    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

    • JPA 2.1 Specs : 8.2 Persistence Unit Packaging
    • JPA 2.1 Specs : 8.2.1.6 mapping-file, jar-file, class, exclude-unlisted-classes

提交回复
热议问题