I agree that PersistenceUnitInfo.getClassLoader() can only help for container managed JPA. In aries jpa we use this mode. We set it to the classloader of the bundle that contains the persistence.xml. This works for all cases I have seen.
For application managed mode I think the ThreadContextClassloader could make sense. If the user knows that he has to set it berfore calling Persistence.createEntityManagerFactory then it should be safe. Maybe there could be a hibernate option to enable using the TCCL. The classloader should only be fetched during this phase from the tccl though and then stored together with the EntityManagerFactory. For OSGi it is always good to provide the user a way to give you the classloader as he then has full control which to use. If you would blindly use the classloader of the class where Persitence.createEntityManagerFactory is called then it may not always be the correct one. Providing a special key name for the classloader to use in the properties that can be given to Persistence.createEntityManagerFactory(java.lang.String persistenceUnitName, java.util.Map properties) would also help a lot.
If you always use a classloader that already exists and that is valid per EntityManagerFactory then there is no need to clean it up. You only should make sure that you delete any reference to it when EntittyManagerFactory.close is called. In case of container managed aries jpa will call the close. In case of application managed the user should call it. I would not auto close the EntityMangerFactory if hibernate did not initiate the create itself.
|