I noticed that calling createEntityManagerFactory(null)
will use the default Persistence Unit (PU) in the configuration file. Sometimes the classpaths get real
I found a way to do it if the provider is hibernate:
Session s=(Session)em.getDelegate();
//Get the URL.
String info=null;
try {
//The wonderful Hibernate team deprecated connection() before giving an alternative.
//Feel free to share the love at http://opensource.atlassian.com/projects/hibernate/browse/HHH-2603
//cf http://opensource.atlassian.com/projects/hibernate/browse/HHH-2603?focusedCommentId=29531&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#action_29531
info=s.connection().getMetaData().getURL();
} catch (Exception e) {
throw new RuntimeException(e);
}
//Finish
em.close();
return info;
Note that em
is an opened EntityManager created from an EntityManagerFactory. Also, like the comments? That's right, the Hibernate team is full of surprises again. Even though users gave feedback begging not to deprecate the only method that can help me, they are going full steam ahead. Note this link.
I'll upvote any good suggestions for a more stable JPA provider. Hibernate is just getting too unstable. This is definitely not the first issue of this kind that I had to workaround.
The problem with Jan's answer is this:
Session s=(Session)em.getDelegate();
Following J2EE api, EntityManager.getDelegate() method : Return the underlying provider object for the EntityManager, if available. The result of this method is implementation specific. The unwrap method is to be preferred for new applications.
Due to the fact that the returned object is implementation specific it may vary so there's no reliable object or attribute from which take persistence unit's name.
I propose another easy way to get. It's as easy as add to the persistence.xml's persistence-units one custom property with it's name as 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");
EntityManager's getProperties() method is a reliable method and not vendor specific so if you set you custom property with the name of your persistence-unit at your persistence.xml you will be able to recover it later in your java code easily.