Hibernate XMLマッピングファイル(hbm.xml)をプログラムで追加する方法

Hibernate XMLマッピングファイル(hbm.xml)をプログラムで追加する方法

Hibernate XMLマッピングファイルには、Javaクラスとデータベーステーブル間のマッピング関係が含まれています。 これは常に「xx.hbm.xml」と名付けられ、Hibernate構成ファイル「hibernate.cfg.xml」で宣言されます。

たとえば、マッピングファイル(hbm.xml)は「mapping」タグで宣言されています




  false
  com.mysql.jdbc.Driver
  password
  jdbc:mysql://localhost:3306/example
  root
  org.hibernate.dialect.MySQLDialect
  true
  

Hibernateマッピングファイル(hbm.xml)をプログラムで追加する

何らかの理由で、マッピングファイルをhibernate.cfg.xmlに含めたくありません。 Hibernateは、開発者がプロ​​グラムでマッピングファイルを追加する方法を提供します。

hbm.xml」ファイルパスを引数としてaddResource()メソッドに渡すことにより、デフォルトのHibernateSessionFactoryクラスを変更するだけです。

SessionFactory sessionFactory = new Configuration()
   .addResource("com/example/common/Stock.hbm.xml")
   .buildSessionFactory();

HibernateUtil.java

HibernateUtil.javaの完全な例として、HibernateXMLマッピングファイル「xx.hbm.xml」をプログラムでロードします。

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {

            SessionFactory sessionFactory = new Configuration()
                    .configure("/com/example/persistence/hibernate.cfg.xml")
                    .addResource("com/example/common/Stock.hbm.xml")
                    .buildSessionFactory();

            return sessionFactory;

        } 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);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void shutdown() {
        // Close caches and connection pools
        getSessionFactory().close();
    }

}

完了しました。