组件关联映射的属性是复杂类型的持久化类,但不是实体类,即数据库中没有表与该属性对应,但该类的属性要持久保存。
比如:外国人的名字name分为firstName和lastName。
MyName.java:
public class MyName {
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
注:这是一个组件类,不和数据库进行映射,它对应People中的name字段。
People.java:
public class People {
private Integer pid;
/*名字通过MyName这个类来组合,即组件关联*/
private MyName name;
public Integer getPid() {
return pid;
}
public void setPid(Integer pid) {
this.pid = pid;
}
public MyName getName() {
return name;
}
public void setName(MyName name) {
this.name = name;
}
}
注:name字段是通过组件(MyName类)关联来是实现的。
People.hbm.xml:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.lixue.bean">
<class name="People" table="t_people">
<id name="pid">
<generator class="native"/>
</id>
<!-- 通过Component来实现主键的映射 -->
<component name="name" class="MyName">
<property name="firstName" />
<property name="lastName" />
</component>
</class>
</hibernate-mapping>
注:组件关联是通过<component>标签来映射的。
测试类:
public void testSave1(){
/*定义Session和事物*/
Session session = null;
Transaction transaction = null;
try {
/*获取Session并开启事物*/
session = HibernateUtils.getSession();
transaction = session.beginTransaction();
/*创建名字*/
MyName myName = new MyName();
myName.setFirstName("乔治");
myName.setLastName("华盛顿");
/*创建人并设置属性*/
People people = new People();
people.setName(myName);
session.save(people);
/*提交事物*/
transaction.commit();
} catch (Exception e) {
e.printStackTrace();
transaction.rollback();
} finally{
HibernateUtils.closeSession(session);
}
}