EntityManager with try-with-resource

try-with-resource is the new feature introduced in Java 1.7 to automatically close a resource after using. It basically helps you to avoid a finally block at the end of the try-catch block to close any resource that needs closing like the BufferedReader. But there’s a catch. You can not use any type of resource with a try-with-resource block, only those classes that extend java.lang.AutoCloseable can be used, an interface that has a single method:

public void close()

Today I was writing a Persistence class that uses javax.persistence.EntityManager. Every time I created an instance of EntityManager, I had to manually close it in a finally block. The EntityManager interface also has a close() method with similar signature as above. Only had there been an alternate EntityManager that extended the AutoCloseable interface, I could have avoided the finally block to close it explicitly. Just a thought!

Advertisements

I am a software engineer, an open-source enthusiast and a hobbyist blogger.

Tagged with: , , , , ,
Posted in Blog, Java
3 comments on “EntityManager with try-with-resource
  1. GeekDeNz says:

    Have you considered this?

    “`
    import javax.persistence.EntityManager;

    /**
    * Make try-with-resource possible for EntityManager
    *
    * @author heuert
    */
    public interface AutoCloseableEntityManager extends EntityManager, AutoCloseable {
    @Override
    public default void close() {
    try {
    this.close();
    } catch (Exception e) {
    throw new RuntimeException(e);
    }
    }
    }
    “`

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 )

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

%d bloggers like this: