Reputation: 8746
Is it possible to get the associated persistence unit name of an EntityManager object? For example, you have
@PersistenceContext( unitName="fooPU" )
private EntityManager em;
Is it possible to get the name fooPU
from em
? The motivation for this is that I want to have a small test to verify that the injected em through @Inject
is associated with the right persistence unit.
Upvotes: 7
Views: 11272
Reputation: 51
You can just add another "property" inside the "properties" part of file persistence.xml.
Example:
<persistence-unit name="pu-foo" transaction-type="JTA">
<jta-data-source>jdbc/some-name</jta-data-source>
<!-- other fields/properties -->
<properties>
<property name="persistence-unit-name" value="pu-foo" />
<!-- other fields/properties -->
</properties>
</persistence-unit>
And, inside your java code, let suppose you have an EntityManager called myEM...
System.out.println(myEM.getEntityManagerFactory().getProperties().get("persistence-unit-name"));
Or...
System.out.println(myEM.getProperties().get("persistence-unit-name"));
The property "persistence-unit-name" appears in properties of both myEM and myEM.getEntityManagerFactory().
That would print "pu-foo"
I hope that could help someone that still have this need.
Upvotes: 0
Reputation: 97
the persistance unit name is under the key "hibernate.ejb.persistenceUnitName" in the properties Map
String puName = em.getEntityManagerFactory().getProperties().get("hibernate.ejb.persistenceUnitName").toString()
Upvotes: 8