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();
}
}
做完了
标签: 冬眠
翻译自: https://mkyong.com/hibernate/how-to-add-hibernate-xml-mapping-file-hbm-xml-programmatically/