Getting Database connection in pure JPA setup

Viewed 142556

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?

13 Answers

Hibernate 4 / 5:

Session session = entityManager.unwrap(Session.class);
session.doWork(connection -> doSomeStuffWith(connection));

I am a little bit new to Spring Boot, I have needing the Connection object to send it to Jasperreport also, after trying the different answers in this post, this was only useful for me and, I hope it helps someone who is stuck at this point.

@Repository
public class GenericRepository {

private final EntityManager entityManager;

@Autowired
public GenericRepository(EntityManager entityManager, DataSource dataSource) {
    this.entityManager = entityManager;
}

public Connection getConnection() throws SQLException {
    Map<String, Object> properties = entityManager.getEntityManagerFactory().getProperties();
    HikariDataSource dataSource = (HikariDataSource) properties.get("javax.persistence.nonJtaDataSource");
    return dataSource.getConnection();
}
}
Related