组件作为联合标识符,必须满足:
它必须实现java.io.Serializable接口
它必须重新实现equals()和hashCode()方法, 始终和组合关键字在数据库中的概念保持一致
你不能使用一个IdentifierGenerator产生组合关键字。一个应用程序必须分配它自己的标识符。
【注意:在Hibernate3中,第二个要求并非是Hibernate强制必须的。但最好这样做。】
<class name="com.jason.compositeId.OrderDetail" table="t_orderdetail">
<composite-id name="id" class="com.jason.compositeId.CompositeId">
<key-property name="orderId" column="order_id" />
<key-property name="itemId" column="item_id" />
</composite-id>
<property name="count" column="count" type="int" />
</class>
<!--
create table t_orderdetail ( order_id bigint not null, item_id bigint not null, count bigint not null, primary key(order_id, item_id) )
-->
public class CompositeId implements Serializable{
private int orderId;
private int itemId;
public int getItemId() {
return itemId;
}
public void setItemId(int itemId) {
this.itemId = itemId;
}
public int getOrderId() {
return orderId;
}
public void setOrderId(int orderId) {
this.orderId = orderId;
}
@Override
public boolean equals(Object obj) {
return super.equals(obj);
}
@Override
public int hashCode() {
return (orderId + itemId)^2;
}
}
public class OrderDetail {
private CompositeId id;
private int count;
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public CompositeId getId() {
return id;
}
public void setId(CompositeId id) {
this.id = id;
}
}