hibernate复合主键的可选值:
<composite-id
name="propertyName"
class="ClassName"
mapped="true|false"
access="field|property|ClassName">
node="element-name|."
<key-property name="propertyName" type="typename" column="column_name"/>
<key-many-to-one name="propertyName class="ClassName" column="column_name"/>
......
</composite-id>
create table composited_id_entity(
foo_id varchar(46) not null,
key_id varchar(46) not null,
name varchar(200) not null,
create_date timestamp,
primary key(foo_id, key_id)
);
当表使用复合字段作为主键时,hibernate声明复合主键,需要使用compositd-id和key-property元素,如:
<class name="CompositedIdEntity" table="composited_id_entity">
<composite-id>
<key-property name="fooId" column="foo_id"/>
<key-property name="keyId" column="key_id"/>
</composite-id>
<property name="name"/>
<property name="date" type="timestamp" column="create_date"/>
</class>
有复合主键的表对应的persistent class要重写hashCode()和equals(),这样才能实现复合键是否相等,
persistent class还要实现Serializable接口。
public class CompositedIdEntity implements Serializable{
private static final long serialVersionUID = 5238531209505340462L;
private String fooId;
private String keyId;
private String name;
private Date date;
public CompositedIdEntity(){}
public CompositedIdEntity(String fooId, String keyId, String name, Date date){
this.fooId = fooId;
this.keyId = keyId;
this.name = name;
this.date = date;
}
//get set method.
@Override
public int hashCode() {
return this.getFooId().hashCode() + this.getKeyId().hashCode();
}
@Override
public boolean equals(Object object) {
if(object == null || !(object instanceof CompositedIdEntity)) return false;
CompositedIdEntity entity = (CompositedIdEntity) object;
return this.getFooId().equals(entity.getFooId()) &&
this.getKeyId().equals(entity.getKeyId()) &&
this.getName().equals(entity.getName()) &&
this.getDate().equals(entity.getDate());
}
}
测试:
java.io.Serializable ser = session.save(
new CompositedIdEntity("d820152b", "0e9dcc", "content", new Date()));
System.out.println(ser);
输出:
org.lam.detector.hibernate.charpter1.model.CompositedIdEntity@d5f398c6
可以看出save()返回了表mapping对应类的对象。