2013年10月22日火曜日

Hibernate 4のSessionFactoryの使い方

Hibernate 4のSessionFactoryはHibernate 3と勝手が違うので、3のやり方で実装するとハマります。例えば、“org.hibernate.HibernateException: createCriteria is not valid without active transaction” exception? のような例外が発生します。

どうやら、<property name="current_session_context_class">thread</property>をhibernate.cfg.xmlに書いていると、トランザクション処理をコードに書かないといけないようです。

※current_session_context_classはまだよく分かってないので後日調べる。

というわけで、
Session session = null;
Transaction tx = null;
try {
  session = sessionFactory.getCurrentSession();                
  Transaction tx = session.beginTransaction();                                     tx.commit();                                                                   
} catch(Exception e) {
  if( tx != null ) { tx.rollback(); }                             
}
トランザクションのコミット、ロールバックは注意して書きましょう。


http://stackoverflow.com/questions/11145935/how-can-i-resolve-org-hibernate-hibernateexception-createcriteria-is-not-valid/11146370#11146370
http://stackoverflow.com/questions/9717906/org-hibernate-hibernateexception-get-is-not-valid-without-active-transaction
http://www.roseindia.net/hibernate/hibernate4/HibernateSessionFactory.shtml

0 件のコメント:

コメントを投稿