2017-05-04 1 views
-1

JPA를 사용하여 작성자 객체를 저장하는 Spring 애플리케이션이 있습니다. 필자는 필자의 데이터베이스 클래스 메서드를 작성하여 올바른 "템플릿"을 사용하여 좋은 작업을 보장합니다. 그러나, 나는 일종의 초보자이고 이것이 항상 필요하거나 심지어 원하는지 확실하지 않습니다. 모범 사례에 대한 의견이나 정보는 언제나 환영합니다!JPA 데이터베이스 클래스 메소드

템플릿

openConnection(); 
    EntityTransaction transaction = this.em.getTransaction(); 
    try { 
     transaction.begin(); 
     //DO STUFF HERE 
     transaction.commit(); 
    } catch (Exception e) { 
     if(transaction.isActive()) { 
      transaction.rollback(); 
     } 
     throw new DatabaseException(e.getMessage(), e); 
    } finally { 
     closeConnection(); 
    } 

이 코드 중 하나를 사용하지 않을 전체 데이터베이스 코드

public class AuthorDatabaseDerby implements AuthorDatabase { 

    private static volatile AuthorDatabaseDerby uniqueInstance; 
    private EntityManagerFactory emf; 
    private EntityManager em; 

    public static AuthorDatabaseDerby getInstance() { 
     if(uniqueInstance == null) { 
      synchronized(AuthorDatabaseDerby.class) { 
       if(uniqueInstance == null) { 
        uniqueInstance = new AuthorDatabaseDerby(); 
       } 
      } 
     } 
     return uniqueInstance; 
    } 

    private AuthorDatabaseDerby() { 
     this.emf = Persistence.createEntityManagerFactory("bookstore"); 
    } 

    private void openConnection() { 
     this.em = this.emf.createEntityManager(); 
    } 

    private void closeConnection() throws DatabaseException { 
     try { 
      if(this.em != null) { 
       this.em.close(); 
      } 
     } catch(Exception e) { 
      throw new DatabaseException(e.getMessage(), e); 
     } 
    } 

    @Override 
    public Author get(int id) throws DatabaseException { 
     openConnection(); 
     EntityTransaction transaction = this.em.getTransaction(); 
     try { 
      transaction.begin(); 
      Author author = this.em.find(Author.class, id); 
      transaction.commit(); 
      return author; 
     } catch (Exception e) { 
      if(transaction.isActive()) { 
       transaction.rollback(); 
      } 
      throw new DatabaseException(e.getMessage(), e); 
     } finally { 
      closeConnection(); 
     } 
    } 

    @Override 
    public List<Author> getAll() throws DatabaseException { 
     openConnection(); 
     EntityTransaction transaction = this.em.getTransaction(); 
     try { 
      transaction.begin(); 
      List<Author> authors = this.em.createQuery("Select a From Author a", Author.class).getResultList(); 
      transaction.commit(); 
      return authors; 
     } catch(Exception e) { 
      if(transaction.isActive()) { 
       transaction.rollback(); 
      } 
      throw new DatabaseException(e.getMessage(), e); 
     } finally { 
      closeConnection(); 
     } 
    } 

    @Override 
    public void add(Author author) throws DatabaseException { 
     openConnection(); 
     EntityTransaction transaction = this.em.getTransaction(); 
     try { 
      transaction.begin(); 
      this.em.persist(author); 
      transaction.commit(); 
     } catch(Exception e) { 
      if(transaction.isActive()) { 
       transaction.rollback(); 
      } 
      throw new DatabaseException(e.getMessage(), e); 
     } finally { 
      closeConnection(); 
     } 
    } 

    @Override 
    public void update(Author author) throws DatabaseException { 
     openConnection(); 
     EntityTransaction transaction = this.em.getTransaction(); 
     try { 
      transaction.begin(); 

      Author a = this.em.find(Author.class, author.getId()); 
      a.setBooks(author.getBooks()); 
      a.setDateBirth(author.getDateBirth()); 
      a.setDateDeceased(author.getDateDeceased()); 
      a.setFirstName(author.getFirstName()); 
      a.setId(author.getId()); 
      a.setLastName(author.getLastName()); 
      a.setNationality(author.getNationality()); 

      transaction.commit(); 
     } catch(Exception e) { 
      if(transaction.isActive()) { 
       transaction.rollback(); 
      } 
      throw new DatabaseException(e.getMessage(), e); 
     } finally { 
      closeConnection(); 
     } 
    } 

    @Override 
    public void delete(int id) throws DatabaseException { 
     openConnection(); 
     EntityTransaction transaction = this.em.getTransaction(); 
     try { 
      transaction.begin(); 
      Author author = this.em.find(Author.class, id); 
      this.em.remove(author); 
      transaction.commit(); 
     } catch(Exception e) { 
      if(transaction.isActive()) { 
       transaction.rollback(); 
      } 
      throw new DatabaseException(e.getMessage(), e); 
     } finally { 
      closeConnection(); 
     } 
    } 

    @Override 
    public void close() throws DatabaseException { 
     try { 
      if(this.emf != null) { 
       this.emf.close(); 
      } 
     } catch(Exception e) { 
      throw new DatabaseException(e.getMessage(), e); 
     } 
    } 

} 
+0

승인이나 조언이나 권장 사항이 아닌 것 같습니다. – duffymo

답변

1

.

템플릿에 Spring 트랜잭션 관리를 선호합니다. 그것은 주석과 구성을 기반으로합니다.

연결 클래스 대신 연결 풀을 사용하고 싶습니다.

스프링에서 이미 사용 가능한 것을 사용할 수있는 코드를 작성해야하는 이유는 무엇입니까? 그들은 당신이나 나보다 나은 코드를 작성합니다. 버그를 발견하는 데 더 많은 사용자층이 있습니다.

+0

답변 해 주셔서 감사합니다. 그러나 이것은 학교 임무이며, 비즈니스 로직을 프레임 워크에서 분리해야하기 때문에 Spring 트랜잭션 관리를 사용할 수 없습니다. –

+0

확인. 물론 여기서 읽은 내용은 무시해도됩니다. 당신은 베스트 프랙티스를 요청했습니다. 당신의 코드는 하나가 아닙니다. 풀링이 없습니다. 이것을 에뮬레이션 할 수있는 더 좋은 예라고 생각할 수 있습니다. Spring 소스 코드를보고 디자인에 대해 어떻게 생각하는지 볼 수 있습니다. – duffymo