Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Java EE 7's core interfaces (EntityManager, ...) extend AutoClosable?

I've wondered about, will Java EE 7's core interfaces extends AutoCloseable or not. (By core interfaces I primarily mean EntityManager and the likes, however I don't know for sure if there are other interfaces or classes that could potentially be closed automatically.)

I think they should and here is the basis of my assumption.

Java 6's Connection doesn't even extend Closeable, however Java 7's Connection extends AutoCloseable (just like several other interfaces in the java.sql package).

Can interfaces like EntityManager extend AutoCloseable in way that it would serve us well, given Java 7's try-with-resources statement? Or closing an EntityManager auto-magically is far too complicated?

Is this particular feature considered to be a part of JSR-342?

like image 422
Kohányi Róbert Avatar asked Dec 08 '11 13:12

Kohányi Róbert


1 Answers

If you're managing your own JPA objects then try-with-resources is a nice thing to have with respect to EntityManagers and to a lesser extent the EntityManagerFactory.

I opted to create a utility that wraps a EntityManagerFactory in a java.lang.reflect.Proxy that implements an AutoCloseable version of the interface. The invocation handler then intercepts calls to createEntityManager() so it can return proxied versions of the underlying EntityManager instances that also implement AutoCloseable.

I think it's much easier working in the world of container managed JPA objects but if you're stuck running in a simple webapp then this may work for you.

like image 130
massfords Avatar answered Sep 28 '22 09:09

massfords