在Hibernate中,component是某个实体的逻辑组成部分,它与实体的根本区别是没有oid(对象标识符),component是一个被包含的对象,它作为值类型被持久化,而非一个实体(摘自网络)
例如网上最常举的例子:类User,Address。一个Address应该是一个User的一部分,在映射中,当然可以把地址单独映射成一张表,与User一对一映射;但是这里最可取的方式,是将Address以组件的方式映射到User中。
类User:
1 public class User {
2
3 private Integer id;
4 private String name;
5 private int age;
6 private Date birth;
7 private Address address;
8
9 // getters...
10 // setters...
11
12 }
类Address:
1 public class Address {
2
3 private String province;
4 private String city;
5 private String county;
6
7 // setters...
8
9 // getters...
10 }
映射文件User.hbm.xml:
1 xml version="1.0"?>
2 DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
3 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
4
5 <hibernate-mapping package&#61;"com.zit.hibernateTest.entities">
6 <class name&#61;"User" table&#61;"USER_5">
7 <id name&#61;"id" type&#61;"java.lang.Integer">
8 <column name&#61;"ID" />
9 <generator class&#61;"increment" />
10 id>
11 <property name&#61;"name" type&#61;"java.lang.String">
12 <column name&#61;"NAME" />
13 property>
14 <property name&#61;"age" type&#61;"int">
15 <column name&#61;"AGE" />
16 property>
17 <property name&#61;"birth" type&#61;"java.util.Date">
18 <column name&#61;"BIRTH" />
19 property>
20
21 <component name&#61;"address" class&#61;"Address">
22 <property name&#61;"province" column&#61;"address_province">property>
23 <property name&#61;"city" column&#61;"address_city">property>
24 <property name&#61;"county" column&#61;"address_county">property>
25 <property name&#61;"street" column&#61;"address_street">property>
26
27 component>
28 class>
29 hibernate-mapping>
User.hbm.xml中&#xff0c;以component子元素将组件Address包含进来&#xff0c;在生成表时&#xff0c;会将Address的属性&#xff0c;映射成User表的字段&#xff0c;与User表中的其他字段平行。
数据库&#xff1a;
PS:
组件映射&#xff0c;Address不生成oid&#xff0c;是值类型&#xff0c;是值类型还是实体类型&#xff0c;并没有非常明显的界线。
将Address以一对一的映射方式映射&#xff08;主键的映射方式、外键的映射方式&#xff09;&#xff0c;也是可以的。