组件映射(User-Name)
关联属性是个复杂类型的持久化类,但不是实体既:数据库中没有表与该属性对应,但该类的属性要持久保存。
当组件映射的属性不能和表中的字段简单对应的时候可以选择实现:
org.hibenrate.usertype.UserType或org.hibernate.usertype.CompositeUserType
1、首先创建domain类:
package com.zhaosoft.domain;
import java.util.Date;
public class User {
private int id;
private Name name;
private Date birthday;
private int ver; //版本号,悲观锁
public int getVer() {
return ver;
}
public void setVer(int ver) {
this.ver = ver;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Name getName() {
return name;
}
public void setName(Name name) {
this.name = name;
}
}
2、实现组件映射对应的类:
package com.zhaosoft.domain;
public class Name {
private String firstName;
private String middleName;
private String lastName;
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
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;
}
}
3、映射关系:
<?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.zhaosoft.domain">
<!-- 当discriminator-value值为0时,为普通员工 -->
<class name="User">
<cache usage="read-only"/>
<id name="id">
<!-- 表示主键为自动增长 -->
<generator class="hilo"/>
</id>
<!--版本号-->
<version name="ver"/>
<property name="birthday" type="date"/>
<!-- 组件映射 -->
<component name="name" class="Name">
<property name="firstName" column="first_name"/>
<property name="middleName" column="middle_name"/>
<property name="lastName" column="last_name"/>
</component>
</class>
<query name="getUserByID">
<![CDATA[from User ]]>
</query>
</hibernate-mapping>