why?

왜? EntityManager는 AutoCloseable 구현하고 있지 않은가?

jay Joon 2021. 6. 15. 14:12

EntityManager는 쓰레드 간에 공유를 하지 않고 사용 후 바로 정리해야 한다고 한다.

public void run(ApplicationArguments args) throws Exception {
    EntityManager em = entityManagerFactory.createEntityManager();
    EntityTransaction transaction = em.getTransaction();

    transaction.begin();
    try {
        Member member = new Member();
        member.setName("kjj");
        em.persist(member);

        transaction.commit();
    } catch (Exception e) {
        transaction.rollback();
    } finally {
        em.close();
    }
}

따라서 위와 같은 코드 try - finally 문이 어쩔 수 없이 강제되는데

 

 

이펙티브 자바의 아이템중

try-finally 보다는 try-with-resources를 사용하라

 

이라는 해당 내용이 존재한다.

 

 

따라서 try-with-resource 문을 사용한다면 더 깔끔하지 않을까?라는 의문이 들어서

사용해보려고 했지만?  현재 EntityManager는 AutoCloseable 구현하고 있지 않다.

 

자바 7 이 2011 년도에 나왔는데 아직까지 추가되지 않았다.

 

혹시 뭔가 다른 이유가 있어서 추가하고 있지 않는 걸까?

 

 

++ 추가

 

https://github.com/eclipse-ee4j/jpa-api/issues/77

 

EntityManager(Factory) should implement AutoCloseable · Issue #77 · eclipse-ee4j/jpa-api

EntityManager and EntityManagerFactory have #close() methods but do not implement AutoCloseable. Implementing AutoCloseable would allow them to be used in Java 7 try-with-resource statement.

github.com

해당 이슈는 2014년에 이미 등록된 이슈이다.

 

 

https://github.com/eclipse-ee4j/jpa-api/pull/312

 

#77: EntityManager(Factory) should implement AutoCloseable by lukasj · Pull Request #312 · eclipse-ee4j/jpa-api

Fixes #77

github.com

또한 이번 2021년 4월 20일에 추가되어 merge 된 것으로 확인된다.

 

변경된 history