先有数据库如下(MS-SQL2005):
-- 创建 person 表
-- 删除 Person 表
DROP TABLE person ;
-- 创建 Person 表
CREATE TABLE person (
name VARCHAR(100) not null ,
phone VARCHAR(50) not null ,
age INT ,
PRIMARY KEY (name,phone)
)
1.向项目的lib目录中添加commons-lang-x.x.x.jar
2.创建Person类,实现
Serializable 接口
复写 equals 和 hashCode 方法
• equals:对象比较方法
• hashCode:取得 Hash 编码
public boolean equals(Object obj)
{
if (this == obj) {
return true;
}
if (!(obj instanceof Person)) {
return false;
}
PersonKey p = (PersonKey) obj;
return new EqualsBuilder().append(this.name, p.getName()).append(this.phone,
p.getPhone()).isEquals();
}
/**
* Implementation of the hashCode method conforming to the Bloch pattern with
* the exception of array properties (these are very unlikely primary key types).
* @return int
*/
public int hashCode()
{
return new HashCodeBuilder().append(this.name).append(
this.phone).toHashCode();
}
-----Person.hbm.xml----
<?xml version="1.0" encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<!-- DO NOT EDIT: This is a generated file that is synchronized -->
<!-- by MyEclipse Hibernate tool integration. -->
<!-- Created Sat Nov 11 21:36:21 CST 2006 -->
<hibernate-mapping package="org.lxh.hibernate03">
<class name="Person" table="PERSON">
<composite-id name="id" class="PersonKey">
<key-property name="name" column="NAME" type="string"/>
<key-property name="phone" column="PHONE" type="string"/>
</composite-id>
<property name="age" column="AGE" type="int" />
</class>
</hibernate-mapping>
注意class="PersonKey
新建类
PersonKey.java
package org.lxh.hibernate03;
import java.io.Serializable;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
public class PersonKey
implements Serializable
{
private volatile int hashValue = 0;
private java.lang.String name;
private java.lang.String phone;
public PersonKey() {}
public java.lang.String getName()
{
return name;
}
public void setName(java.lang.String name)
{
hashValue = 0;
this.name = name;
}
public java.lang.String getPhone()
{
return phone;
}
public void setPhone(java.lang.String phone)
{
hashValue = 0;
this.phone = phone;
}
public boolean equals(Object obj)
{
if (this == obj) {
return true;
}
if (!(obj instanceof Person)) {
return false;
}
PersonKey p = (PersonKey) obj;
return new EqualsBuilder().append(this.name, p.getName()).append(this.phone,
p.getPhone()).isEquals();
}
public int hashCode()
{
return new HashCodeBuilder().append(this.name).append(
this.phone).toHashCode();
}
}
Person.java
private PersonKey id ;
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public PersonKey getId() {
return id;
}
public void setId(PersonKey id) {
this.id = id;
}