How to retrieve the datasource used by a persistence unit programmatically

后端 未结 10 1503
旧时难觅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-07 23:48

    You need to:

    1. cast the EntityManager to EntityManagerImpl (the Hibernate implementation)
    2. call getFactory()
    3. cast the EntityManagerFactory to HibernateEntityManagerFactory
    4. call getSessionFactory() and cast it to SessionFactoryImpl
    5. call getConnectionProvider() and cast it to the correct implementation. You can see the implementations here. I'll assume that it's a DatasourceConnectionProvider
    6. call getDataSource() and you're done.

    Unfortunately, you must use the Hibernate API, as there's no way to retrieve the DataSource using the JPA API.

提交回复
热议问题