Obtaining a JDBC Connection in Hibernate and OpenJPA

This post is on how to obtain/instantiate a JDBC connection in Hibernate framework or in OpenJPA framework.

Test context

  • Hibernate 3.x
  • OpenJPA 1.2.x

Hibernate

Session session = new Configuration().buildSessionFactory().openSession();
session.doWork(new Work() {
    @Override
    public void execute(Connection connection) throws SQLException {
        // do something with connection
    }
});

OpenJPA

EntityManager manager = getEntityManagerFactory("unit-name").createEntityManager();
Connection connection = (Connection) OpenJPAPersistence.cast(manager).getConnection();
// do something with connection

References

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s