组件(Component)映射

本文介绍了Hibernate中的Component概念,它是实体的逻辑组成部分,没有独立的oid。Component以值类型方式被持久化,并通过<component>标签进行映射。文中通过Teacher类为例,展示了Component的使用,并进行了保存操作的测试,详细解释了Component在数据库表结构中的体现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在hibernate中,Component是某个实体的逻辑组成部分,它与实体的根本区别是没有oid(对象标识符),Component是一个被包含的对象,它作为值类型被持久化,而非一个实体。

在hibernate中Component映射采用<component>标签即可。

示例:

1、类Teacher

public class Teacher {
	private int id;
	private String name;
	private String sex;
	private Address address;
	//省略get/set方法
}
2、类Teacher的组件Address

public class Address {
	private String addr1;
	private String addr2;
	private String addr3;
        //省略get/set
}
3、Teacher.hbm.xml配置

<hibernate-mapping package="com.test.pojo">
	<class name="Teacher">
		<id name="id">
			<generator class="native"></generator>
		</id>
		<property name="name" />
		<property name="sex" />
		<!-- 组件 -->
		<component name="address" class="Address">
			<property name="addr1" />
			<property name="addr2" />
			<property name="addr3" />
		</component>
	</class>
</hibernate-mapping>
4、HibernateUtil

public class HibernateUtil {
	private static Configuration cfg=null;
	private static SessionFactory factory=null;
	private static Session session=null;
	static{
		cfg=new Configuration().configure();
		factory=cfg.buildSessionFactory(new StandardServiceRegistryBuilder()
		.applySettings(cfg.getProperties()).build());
	}
	public static Session getSession(){
		if(factory!=null)
			return factory.openSession();
		factory=cfg.buildSessionFactory(new StandardServiceRegistryBuilder()
		.applySettings(cfg.getProperties()).build());
		return factory.openSession();
	}
	public static void closeSession(){
		if(session!=null && session.isOpen())
			session.close();
	}
}

5、测试

public class HibernateTest {
	@Test
	public void testCreateDB(){
		Configuration cfg=new Configuration().configure();
		SchemaExport se=new SchemaExport(cfg);
		//第一个参数表示是否生成ddl脚本,第二个参数表示是否执行到数据库中
		se.create(true, true);
	}
	/**
	 * 保存数据
	 */
	@Test
	public void save(){
		Session session=null;
		Transaction tx=null;
		try{
			session=HibernateUtil.getSession();
			tx=session.beginTransaction();
			Teacher t=new Teacher();
			t.setName("张三");
			t.setSex("男");
			Address address=new Address();
			address.setAddr1("丰台");
			address.setAddr2("朝阳");
			address.setAddr3("海淀");
			t.setAddress(address);
			session.save(t);
			tx.commit();
		}catch(Exception e){
			if(tx!=null)
				tx.rollback();
			e.printStackTrace();
		}finally{
			HibernateUtil.closeSession();
		}
	}
}
执行testCreateDB控制台打印信息如下:



执行save控制台打印信息如下:


数据库表结构如下:









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值