How to retrieve the datasource used by a persistence unit programmatically

后端 未结 10 1536
旧时难觅i
旧时难觅i 2020-12-07 23:05

...without actually reading and parsing the persistence.xml

I can retrieve the name of the persistence unit of an EntityManager using the p

10条回答
  •  天命终不由人
    2020-12-08 00:00

    In a Spring environment you can use this:

    import org.springframework.orm.jpa.EntityManagerFactoryInfo;
    ...
    
    @PersistenceContext
    EntityManager entityManager;
    
    public DataSource getDataSourceFromHibernateEntityManager() {
       EntityManagerFactoryInfo info = (EntityManagerFactoryInfo) entityManager.getEntityManagerFactory();
       return info.getDataSource();
    }
    

提交回复
热议问题