The problem with Jan's answer is this:
Session s = (session) em.getDelegate ();
Following the J2EE api, EntityManager.getDelegate (): Returns the main provider object for the EntityManager, if available. The result of this method is a concrete implementation. The deployment method should be preferred for new applications.
Due to the fact that the returned object is implementation-specific, it can change, so there is no reliable object or attribute from which the name of the storage unit follows.
I suggest another easy way to get. This is as simple as adding one custom property called name to persistence.xml persistence-units in the following example:
<persistence-unit name="PERSISTENCE_UNIT" transaction-type="JTA"> <jta-data-source>DATASOURCE</jta-data-source> <class>com.package.EntityClass</class> <properties> <property name="PERSISTENCE_UNIT_NAME" value="THE NAME OF MY PERSISTENCE UNIT"/> </properties> </persistence-unit> </persistence>
and in your java code:
Map<String, Object> propertiesMap = entityManagerInstance.getProperties(); String persistenceUnitName = (String)propertiesMap.get("PERSISTENCE_UNIT_NAME");
The EntityManager getProperties () method is a reliable method and not vendor specific, so if you configure your own resource with the name of your persistence unit in your persistence.xml, you can easily restore it later in your java code.
source share