How to retrieve the datasource used by a persistence unit programmatically

后端 未结 10 1505
旧时难觅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:58
    DataSource dataSource = (DataSource) 
    em.getEntityManagerFactory().getProperties()
                .get(org.hibernate.cfg.AvailableSettings.JPA_JTA_DATASOURCE);
    

    You can retrieve datasoure with hibernate. Tested with Hibernate 5.3

    0 讨论(0)
  • 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();
    }
    
    0 讨论(0)
  • 2020-12-08 00:02

    in SpringBoot environment you can use the following:

    @PersistenceContext
    EntityManager entityManager;
    
    private HikariDataSource getDataSourceFromHibernateEntityManager() {
        EntityManagerFactoryInfo info = (EntityManagerFactoryInfo) entityManager.getEntityManagerFactory();
        return (HikariDataSource) info.getDataSource();
    }
    
    public String getDataSourceProperties() {
        HikariDataSource dataSource = getDataSourceFromHibernateEntityManager();
        return "DataSource properties:" +
                "URL: " + dataSource.getJdbcUrl() + "\n" +
                "Default Schema: " + dataSource.getPoolName() + "\n" +
                "Driver Class Name: " + dataSource.getDriverClassName() + "\n" +
                "Username: " + dataSource.getUsername() + "\n";
    }
    
    0 讨论(0)
  • 2020-12-08 00:03

    Here's what helped me. I use HikariCP but I don't think it matters.

    Basically what needs to be done is

    1. find a service registry
    2. get service by org.hibernate.engine.jdbc.connections.spi.ConnectionProvider class
    3. unwrap it to javax.sql.DataSource.

    Service registry can be retrieved from EntityManager

    ((SessionImpl) em).getFactory().getServiceRegistry()
    

    or from EntityManagerFactory directly

    ((SessionFactoryImpl) entityManagerFactory).getServiceRegistry()
    
    0 讨论(0)
提交回复
热议问题