1

I have a Spring Boot/Hibernate environment. For an additional native SQL query besides the existing model I need one of Hibernates SQL connections from the pool. Is there a way to get a connection from the existing pool via EntityManager, Session or another class? I don't want to create a second pool or initialize a separate connection (needs a lot of resources and time and is going to be done several times).

SpringBoot-Version is 1.4.7

Hibernate JPA is 2.1

I am already searching the whole day and can't find a solution.

Thanks and bye

  • Spring Boot is already shipped with HikariCP, hence connections are normally served using this Connection Pool. Hence I would simply get a handle on the factory, initialize a session and write the SQL. https://stackoverflow.com/questions/25063995/spring-boot-handle-to-hibernate-sessionfactory – Ph03n1x May 16 '18 at 11:40
  • That would work, if I would execute the SQL myself. The problem is, that it is a 3rd party library which requires a object implementing the java.sql.Connection interface. Is it possible to make something like `entityManager.unwrap(java.sql.Connection.class)`? – Andreas Gottardi May 16 '18 at 12:13
  • Just inject a `JdbcTemplate` and wrap the call you want to do in a `ConnectionCallback` that will give you a managed connection and when there is an ongoing transaction you will get the current used `Connection`. – M. Deinum May 16 '18 at 13:41
  • I don't want to interfere with ongoing connections of hibernate/jpa. That was my concern. I think we will just reduce the connection pool size of hibernate and make a 2nd pool. I already got a code sample running which creates a pool and serves connections. Thanks for the help! – Andreas Gottardi May 18 '18 at 08:46

0 Answers0