2013-01-02 5 views
1

Hibernate를 일반적으로 사용하는 올바른 방법은 무엇인가에 대한 많은 예제, 튜토리얼 및 코멘트가 있습니다. 그래서 나는 당신이 내 코드를보고 그것을 올바르게 사용하고 있는지 또는 잘못된 방법으로 사용하고 있는지 확인해주기 바란다.
EDIT 최대 절전 모드를 혼자 사용하고 있습니다. 4 최대 절전 모드 :)Hibernate를 사용하는 "올바른 방법"

public class HibernateUtil { 

private static SessionFactory sessionFactory = buildSessionFactory(); 


private static SessionFactory buildSessionFactory() { 
try { 
    // Create the SessionFactory from hibernate.cfg.xml 
    System.out.println("Building new SessionFactory !!"); 
    Configuration configuration = null; 
    ServiceRegistry serviceRegistry = null; 
    try{ 

     configuration = new Configuration(); 

      configuration.configure(); 
     serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); 
    }catch(Exception e){ 
     e.printStackTrace(); 
    } 

    return new Configuration().configure().buildSessionFactory(serviceRegistry); 

} 
catch (Throwable ex) { 
    // Make sure you log the exception, as it might be swallowed 
    System.err.println("Initial SessionFactory creation failed." + ex); 
    throw new ExceptionInInitializerError(ex); 
} 
} 


//Since thread unsafe 
/** 
* thread safe or unsafe ? 
* assuming thread safe 
* @return 
*/ 
public static SessionFactory getSessionFactory() { 

    return sessionFactory; 

} 

public static void tryCloseAll(Session s, Transaction t){ 

    try{ 

     if(t!=null){ 
      if(t.isActive()){ 
       //? 
       try{ 
        t.commit(); 
        System.out.println("HibernateUtil.tryCloseAll():: Transaction successfully committed."); 
       }catch(Exception e){ 
        System.out.println("HibernateUtil.tryCloseAll():: Exception thrown while trying to commit a transaction."); 
       }finally{ 
        t = null; 
        System.out.println("HibernateUtil.tryCloseAll():: Transaction successfully nullified."); 
       } 
      } 

     }else{ 
      System.out.println("HibernateUtil.tryCloseAll():: The method has received a null transaction"); 
     } 

     if(s!=null){ 
      if(s.isOpen()){ 
       try{ 
        s.close(); 
        System.out.println("HibernateUtil.tryCloseAll():: Session successfully closed."); 
       }catch(Exception e){ 
        System.out.println("HibernateUtil.tryCloseAll():: Tried to close session and failed"); 
       }finally{ 
        s = null; 
        System.out.println("HibernateUtil.tryCloseAll():: Session successfully nullified."); 
       } 
      } 
     }else{ 
      System.out.println("HibernateUtil.tryCloseAll():: The method has received a null session"); 
     } 


    }catch(Exception e){ 

    } 
} 

내 DAO 클래스

public class SuperItemDAO extends MSSQLDAO implements InterfaceSuperItemDAO{ 
private SessionFactory sessionFactory = null; 

public static SuperItemDAO getInstance(){ 

    if(INSTANCE == null){ 
     INSTANCE = new SuperItemDAO(); 
    } 

    return INSTANCE; 
} 

SuperItemDAO(){ 

    if(sessionFactory == null){ 
     sessionFactory = HibernateUtil.getSessionFactory(); 
    } 
} 
public SuperItemVO get(int id){ 
     SuperItemVO sivo = null; 
     Session session = null; 
     Transaction transaction = null; 
     try{ 
     session = sessionFactory.getCurrentSession(); 
     transaction = session.getTransaction(); 
     transaction.begin(); 

     Criteria criteria = session.createCriteria(SuperItemVO.class); 
     criteria.add(Restrictions.eq("id", id)); 
     sivo = (SuperItemVO)criteria.uniqueResult(); 

     transaction.commit(); 
    }catch(Exception e){e.printStackTrace();}finally{HibernateUtil.tryCloseAll(session, transaction);} 

    return sivo; 

} 
+0

최대 절전 모드를 단독으로 사용 하시겠습니까? 아니면 스프링으로 사용합니까? – Sikorski

+0

@Sikorski, 내 편집 좀 봐. – Ascendant

+3

'올바른 방법'은 최대 절전 모드를 사용하지 마십시오. – jackalope

답변

2

나는 당신이 당신의 트랜잭션 관리를위한 최대 절전 모드와 함께 스프링 트랜잭션을 사용하는 것이 좋습니다. 그렇지 않으면 거래를 관리하는 야간 거래입니다.

또한 Hibernate를 사용하는 또 다른 올바른 방법은 XML 파일 대신 주석을 사용하여 코드를 매우 직관적이고 관리하기 쉽게 만드는 것입니다.

또한 Java 레이어의 표준이므로 JPA와 hibernate를 함께 사용하는 것이 좋습니다. 참고로

+0

흠 나는 단지 나는 그들 모두를 한번에 배우는 것이 보였으므로 먼저 나는 Hibernate, Spring, JPA 등등 익숙해 졌을 것이다. 불필요하게 어렵다. 의견을 보내 주셔서 감사합니다. 나는 너의 제안을 고려할 것이다. – Ascendant

+0

@ PerfectGundam 어디에서 왔는지 이해합니다. 나는 같은 사이클을 겪어왔다. 어노테이션을 사용하여 저를 믿으시면 학습 곡선이 완전히 사라집니다. 그리고 나중에는 개발이 빨라질 것입니다. 그리고 당신은 이미 최신 기술에 종사하고 있습니다. – Deepak

+0

@Deepak FYI : "학습 곡선 가속화"= "학습 열심히". –

0

:이 부분 :

Criteria criteria = session.createCriteria(SuperItemVO.class); 
    criteria.add(Restrictions.eq("id", id)); 
    sivo = (SuperItemVO)criteria.uniqueResult(); 

더 나은 캐싱을 최대한 활용 할 수있는, 더 나은 당신이 가독성 관점에서 무슨 일을하는지 나타내는 단일 호출로 표현된다.

+0

올바른 점을 이해했다면 하단에있는 메서드가 캐시되고 더 읽기 쉽습니다. – Ascendant

+0

예, 그렇습니다. 하단의 데이터베이스는 심지어 데이터베이스에 갈 필요조차 없습니다. 맨 위의 캐싱은 일부 캐싱을 활용할 수 있지만 SuperItemVO의 관계에서만 가능합니다 (있는 경우). – Matt

+0

지적 해 주셔서 감사합니다 :) – Ascendant

관련 문제