ラベル Hibernate4 の投稿を表示しています。 すべての投稿を表示
ラベル Hibernate4 の投稿を表示しています。 すべての投稿を表示

2013年10月22日火曜日

applicationContext.xmlとhibernate.cfg.xmlとSessionBeanでちょっと手こずった

Spring MVC 3とHibernate 4を設定してる時に、設定ファイルの分割などやちょっとハマったところをメモ。

※この辺のフレームワークはメジャーバージョンアップしたりすると、やり方が変わったりパッケージ名も変わるので厄介。そしてドキュメントも散財していて分からん。。。

まず設定ファイルの分割。Hibernate 3の時は、

applicationContext.xml
hibernate.cfg.xml
jdbc.properties

と分割してたけど、

applicationContext.xml
database1.cfg.xml
database2.cfg.xml
..
..
という構成に分割。jdbc.propertiesは捨てて、なるべくHibernateのコンフィグファイルに書いてやろうと思いました。そして、データベース(スキーマ)毎にSessionFactoryを分割。

※jdbc.propertiesまであると、なんかコンフィグファイルが多く感じで分かりくいから捨てた。


    <bean id="sessionFactory1"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="configLocation">
            <value>/WEB-INF/database1.cfg.xml</value>
        </property>
    </bean>

そしてハマったところ。。。

Hibernate3とHibernate4はパッケージ名が違った。。。気が付かなかった。。。泣ける。。

org.springframework.orm.hibernate3.LocalSessionFactoryBean
じゃなくって、
org.springframework.orm.hibernate4.LocalSessionFactoryBean

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