We have a JPA application (using hibernate) and we need to pass a call to a legacy reporting tool that needs a JDBC database connection as a parameter. Is there a simple way to get access to the JDBC connection hibernate has setup?
First, we need to obtain an instance of EntityManagerFactory that represents the relevant database and then we can use that factory instance to get an EntityManager instance. JPA requires the definition of a persistence unit in an XML file in order to be able to generate an EntityManagerFactory.
If we want to use JPA with MySQL database, we need the mysql-connector-java dependency. We'll also need to define the DataSource configuration. We can do this in a @Configuration class or by using standard Spring Boot properties. Spring Boot will automatically configure a data source based on these properties.
You can use the Create EJB 3. x Session Bean wizard to create a session bean and a JPA entity in your EJB project.
JDBC allows us to write SQL commands to read data from and update data to a relational database. JPA, unlike JDBC, allows developers to construct database-driven Java programs utilizing object-oriented semantics.
As per the hibernate
docs here,
Connection connection()
Deprecated. (scheduled for removal in 4.x). Replacement depends on need; for doing direct JDBC stuff use doWork(org.hibernate.jdbc.Work) ...
Use Hibernate Work API instead:
Session session = entityManager.unwrap(Session.class); session.doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { // do whatever you need to do with the connection } });
Where you want to get that connection is unclear. One possibility would be to get it from the underlying Hibernate Session
used by the EntityManager
. With JPA 1.0, you'll have to do something like this:
Session session = (Session)em.getDelegate(); Connection conn = session.connection();
Note that the getDelegate()
is not portable, the result of this method is implementation specific: the above code works in JBoss, for GlassFish you'd have to adapt it - have a look at Be careful while using EntityManager.getDelegate().
In JPA 2.0, things are a bit better and you can do the following:
Connection conn = em.unwrap(Session.class).connection();
If you are running inside a container, you could also perform a lookup on the configured DataSource
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With