通常做法是将主键相关字段放到一个单独的类中,但是这样类是有要求的:
* 必须实现序列化接口
* 覆盖equals和hashcode方法
示例:TObject类有复合主键aPK、bPK
TObject类:
public class TObject {
private CompositePK compositePK;
private String name;
public CompositePK getCompositePK() {
return compositePK;
}
public void setCompositePK(CompositePK compositePK) {
this.compositePK = compositePK;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
CompositePK类:
public class CompositePK implements Serializable {
private int aPK;
private int bPK;
public int getaPK() {
return aPK;
}
public void setaPK(int aPK) {
this.aPK = aPK;
}
public int getbPK() {
return bPK;
}
public void setbPK(int bPK) {
this.bPK = bPK;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + aPK;
result = prime * result + bPK;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final CompositePK other = (CompositePK) obj;
if (aPK != other.aPK)
return false;
if (bPK != other.bPK)
return false;
return true;
}
}
TObject.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>
<class name="com.zero.hibernate.vo.TObject" table="t_tobject">
<composite-id name="compositePK">
<key-property name="aPK"/>
<key-property name="bPK"/>
</composite-id>
<property name="name" />
</class>
</hibernate-mapping>
生成的建表语句:
drop table if exists t_tobject
create table t_tobject (
aPK integer not null,
bPK integer not null,
name varchar(255),
primary key (aPK, bPK)
)
测试:
TObject tObject = new TObject();
CompositePK pk = new CompositePK();
pk.setaPK(1234);
pk.setbPK(1235);
tObject.setCompositePK(pk);
session.save(tObject);
CompositePK pk = new CompositePK();
pk.setaPK(1234);
pk.setbPK(1235);
TObject tObject=(TObject) session.load(TObject.class, pk);
System.out.println(tObject.getName());
//Hibernate: select tobject0_.aPK as aPK1_0_0_, tobject0_.bPK as bPK2_0_0_, tobject0_.name as name3_0_0_ from t_tobject tobject0_ where tobject0_.aPK=? and tobject0_.bPK=?
//zero