Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Database connection in pure JPA setup

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?

like image 590
Jay Avatar asked Aug 16 '10 13:08

Jay


People also ask

How does JPA connect to database?

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.

How can you connect spring boot to the database using JPA?

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.

What is the type of bean associated with a database connection when using JPA?

You can use the Create EJB 3. x Session Bean wizard to create a session bean and a JPA entity in your EJB project.

Which is the best way to connect JDBC or JPA?

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.


2 Answers

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     } }); 
like image 133
Dominik Avatar answered Oct 22 '22 05:10

Dominik


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.

like image 31
Pascal Thivent Avatar answered Oct 22 '22 07:10

Pascal Thivent