How to get persistence unit name from EntityManager
Asked Answered
C

2

7

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.

Cornhusking answered 9/11, 2013 at 7:6 Comment(4)
From the top of my head, the properties of the EMFactory (entityManager.getEntityManagerFactory().getProperties()) might contain the PU nameGreeley
@kostja: Thanks. As a matter of fact, that is my current workaround, except that I don't have the getEntityManagerFactory(), i.e., I use entityManager.getProperties(), which gives the same property map as yours. But that map doesn't have a standalone PU name key. It does have the PU name embedded in some other keys, though. You can get the PU name with some hacking, but it just doesn't seem clean to me.Cornhusking
Yeah, clean would be different :) Unfortunately, I am not aware of a different way.Greeley
I know it's a bit old post but you can consider asking JPA EG about providing such feature. If it's easy to add - why not try asking for it. If it's not possible because of some reasons it would also be nice to know why.Mensurable
H
8

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()
Holocaine answered 7/8, 2014 at 0:32 Comment(1)
What if the JPA provider is not hibernate, like EclipseLink?Cornhusking
D
0

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.

Dilute answered 3/7 at 17:59 Comment(1)
This won't work if you edit <persistence-unit name="pu-foo"> and overlook the <property>.Essay

© 2022 - 2024 — McMap. All rights reserved.