hibernate复合主键

    如果要实现复合主键,首先要在主键类实现Serializable接口并且复写equals和hashcode。equals和hashCode的复写可以使用第三方工具commons-lang-1.0.1.jar。

举例:

(1)创建一个person表,主键为name和phone

 

create table person(
  name varchar2(30) not null,
  phone varchar2(20) not null,
  age number(30),
  primary key(name,phone) 
)

 

(2)新建主键类PrimaryKey.java(注意要实现Serializable接口并且复写equals和hashcode)

public class PrimaryKey implements Serializable{
   private String name;
   private String phone;
public String getName() {
	return name;
}
public void setName(String name) {
	this.name = name;
}
public String getPhone() {
	return phone;
}
public void setPhone(String phone) {
	this.phone = phone;
}
public boolean equals(Object obj) {
	if(obj == null){
		return false;
	}else if(! (obj instanceof CompositePerson)){
		return false;
	}
	PrimaryKey pk = (PrimaryKey)obj;
	new EqualsBuilder().append(this.name, pk.getName()).append(this.phone,pk.getPhone())
	                   .isEquals();
	return true;
}
@Override
public int hashCode() {
	return new HashCodeBuilder().append(this.name).append(this.phone)
	          .toHashCode();
}

}

 (3) 新建person表对应的pojo(Person.java)

public class Person {
  
	private PrimaryKey primaryKey;
  
	private int age;
	
	public PrimaryKey getPrimaryKey() {
		return primaryKey;
	}
	public void setPrimaryKey(PrimaryKey primaryKey) {
		this.primaryKey = primaryKey;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
}

 (4)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" >
<hibernate-mapping package="包名">

    <class name="Person" table="Person">
       <composite-id name="primaryKey" class="PrimaryKey">
         <key-property name="name" column="name" type="string"/>
         <key-property name="phone" column="phone"/>
       </composite-id>
       <property name="age" column="age" type="int"/>
    </class>
    
</hibernate-mapping>

 

你可能感兴趣的:(Hibernate,xml,.net)