Showing posts with label JPA. Show all posts
Showing posts with label JPA. Show all posts

Jun 14, 2013

Getting JDBC SQL Connection in JPA with Hibernate

When you need to retrieve the plain Connection from JPA, unfortunately, there is no JPA standard way (unless you get a configured datasource with JNDI). This is needed when you use libraries or legacy applications which use JDBC instead of JPA.


Hibernate 3.x and JPA 1.0

With Hibernate you can get the org.hibernate.session. In pre Hibernate 4.o there was the connection() method which now is removed.
EntityManager em = ...;
Session session = (Session) em.getDelegate();
Connection conn = session.connection();

Hibernate 3.x and JPA 2.0

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

Hibernate 4.x and JPA 2.0

Session session = em.unwrap(Session.class);
SessionFactoryImplementor sfi = (SessionFactoryImplementor) session.getSessionFactory();
ConnectionProvider cp = sfi.getConnectionProvider();
Connection conn = cp.getConnection();

JNDI-Lookup

If you are running inside a container, you could also perform a JNDI lookup on the configured DataSource.

Jun 13, 2013

Java aktuell: "Lightweight AOP mit CDI und JPA"

Check out my article of the German magazine "Java aktuell – Das iJUG Magazin" (Ausgabe 03/2013) on


Feel free to contact me on questions and suggestions... (mail: hel@'this.domain')


Feb 20, 2013

Usage of em.flush() in JPA

Suppose you have an JPA EntityManager named em. When you call em.persist() / em.merge() / em.remove() the corresponding SQL instructions insert / update / delete are not immediately sent to the database. Instead, they are cached for performance reasons and executed when you commit the transaction on Java-side (when exactly is dependent on the JPA implementation).

This can be a problem in the following scenarios:
  •  if you do something between the em.persist() and the commit that cannot be undone, i.e. is not transactional itself (like sending an email). If possible, do such things after the successful database transaction!
  • you need the result of some side effects, like an autogenerated key, database trigger, etc.
In these cases you may want that the SQLs are executed immediately: You can do this with em.flush(), which empties the internal SQL cache, sends it to the database and also synchronizes the persistence context.

Feb 19, 2013

JUGM Talk: Lightweight AOP with CDI and JPA

Thank you for the great organization with pizza @JUGM, the plenty attendees and the interesting discussions. Here are the slides: