Friday, March 22, 2019

JPA : Hibernate implementation raises exception when retrieving jdbc connection

For some cases, there a need to retrieve jdbc connection to execute some database operations such as batch works; tables loading from big files or others .....

When working with enitity manager

Connection conn = em.unwrap(Session.class).connection();  

raises an exception when working with an hibernate implementation (works fine with eclipselink)
One solution is :

public Connection hibernateConnection() {
  SessionImplementor si = (SessionImplementor) entityManager.unwrap(Session.class);
  try {
   return si.getJdbcConnectionAccess().obtainConnection();
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   return null;
  }
  
  
 }

No comments:

Post a Comment