JPA EntityManager.unwrap()-method

Last week I came in touch with the very useful


-method from the javax.persistence-package. The method can be used to gain access of JPA-vendor-specific classes. At work, we are running Hibernate in “JPA-mode” which means we do only have access to methods that are provided by the EntityManager-interface. It was ok to us, until we wanted to get rid of those SELECT-statements that the EntityManager.merge()-method does before the UPDATE-statement is fired to the database. If we were running Hibernate in “Hibernate-mode” we wouldn’t have any problems at all: the EntityManager-equivalent Session-class offers a update()-method which fires only the UPDATE-Statement without any SELECTs. This is where the unwrap-method comes into play. Just fetch an EntityManager-instance via injection or create a new one on your own via EntityManagerFactory and place the following snippet into your code:

EntityManager em = ...
Session session = em.unwrap(Session.class);

Thanks to axtavt for his/her advice.


2 thoughts on “JPA EntityManager.unwrap()-method”

  1. You know that you don’t need to do this?

    If you working within a transaction on an attached entity (that is an entity you got from the database), the entity will be updated at the end of a transaction. No need to manually merge it.
    A merge is needed if you created a new Entity(); filled attributes (and ID attributes(!)) from an existing record. This thing needs to be merged if you intend an update.

    So this will update the foobar column:

    Entity entity = entityManager.find(Entity.class, 1);

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s