How to retrieve the datasource used by a persistence unit programmatically

后端 未结 10 1532
旧时难觅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: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";
    }
    

提交回复
热议问题