Finding the current persistence unit for the current EntityManagerFactory

后端 未结 2 966
长情又很酷
长情又很酷 2021-01-19 07:11

I noticed that calling createEntityManagerFactory(null) will use the default Persistence Unit (PU) in the configuration file. Sometimes the classpaths get real

2条回答
  •  盖世英雄少女心
    2021-01-19 07:33

    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:

    
        DATASOURCE
        com.package.EntityClass
        
            
        
      
    
    

    and in your java code:

    Map 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.

提交回复
热议问题