How to retrieve the datasource used by a persistence unit programmatically

后端 未结 10 1533
旧时难觅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:54

    I'm using Hibernate 5.0.x

    This is how I'm getting a connection from the persistence pool:

    import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
    import org.hibernate.jpa.internal.EntityManagerFactoryImpl;
    
    public Connection getConnection(EntityManagerFactory emf) throws SQLException
    {
        final EntityManagerFactoryImpl hibernateEmf = (EntityManagerFactoryImpl) emf;
        return hibernateEmf.getSessionFactory().getServiceRegistry().getService(ConnectionProvider.class).getConnection();
    }
    

    The emf parameter is JPA's standard javax.persistence.EntityManagerFactory, typically acquired globally using:

    emf = Persistence.createEntityManagerFactory("persistence-unit-name");
    

    or by injection:

    @PersistenceUnit(unitName="persistence-unit-name")
    EntityManagerFactory emf;
    

提交回复
热议问题