如何以编程方式添加Hibernate XML映射文件(hbm.xml)

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/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值