Hibernate XMLマッピングファイルには、Javaクラスとデータベーステーブルの間のマッピング関係が含まれています。これは常に “xx.hbm.xml”と命名され、Hibernate設定ファイル “hibernate.cfg.xml”で宣言されます。
たとえば、マッピングファイル(hbm.xml)は ”
mapping
“タグで宣言されています
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.bytecode.use__reflection__optimizer">false</property> <property name="hibernate.connection.driver__class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.password">password</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mkyong</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="show__sql">true</property> <mapping resource="com/mkyong/common/Stock.hbm.xml"></mapping> </session-factory> </hibernate-configuration>
Hibernateのマッピングファイル(hbm.xml)をプログラムで追加する
何らかの理由で、マッピングファイルを `hibernate.cfg.xml`に含めたくないのです。 Hibernateは、開発者がプログラムでマッピングファイルを追加する方法を提供します。
”
hbm.xml
“ファイルパスを引数として `addResource()`メソッドに渡して、デフォルトのHibernate `SessionFactory`クラスを変更するだけです:
SessionFactory sessionFactory = new Configuration()
.addResource("com/mkyong/common/Stock.hbm.xml")
.buildSessionFactory();
HibernateUtil.java
`HibernateUtil.java`の完全な例は、HibernateのXMLマッピングファイル” 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/mkyong/persistence/hibernate.cfg.xml")
.addResource("com/mkyong/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();
}
}
完了しました。