你说
我在为 SubPart 表定义复合键时遇到问题
当你有一个复合主键时,你必须定义一个类(通常是一个静态内部类)来定义你的复合主键(只是一个建议:因为 Hibernate 使用代理,所以更喜欢将你的带注释的映射放在 getter 而不是字段上成员)
/**
* When both entity class and target table SHARE the same name
* You do not need @Table annotation
*/
@Entity
public class SubPart implements Serializable {
@EmbeddedId
private SubPartId subPartId;
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="PART_ID", insertable=false, updateable=false)
private Part part;
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="SUP_PART_ID", insertable=false, updateable=false)
private SubPart subPart;
/**
* required no-arg constructor
*/
public SubPart() {}
public SubPart(SubPartId subPartId) {
this.subPartId = subPartId;
}
// getter's and setter's
/**
* It MUST implements Serializable
* It MUST overrides equals and hashCode method
* It MUST has a no-arg constructor
*
* Hibernate/JPA 1.0 does not support automatic generation of compound primary key
* You SHOULD set up manually
*/
@Embeddable
public static class SubPartId implements Serializable {
@Column(name="PART_ID", updateable=false, nullable=false)
private Integer partId;
@Column(name="SUB_PART_ID", updateable=false, nullable=false)
private Integer subPartId;
/**
* required no-arg constructor
*/
public SubPartId() {}
public SubPartId(Integer partId, Integer subPartId) {
this.partId = partId;
this.subPartId = subPartId;
}
// getter's and setter's
@Override
public boolean equals(Object o) {
if(!(o instanceof SubPartId))
return null;
final SubPartId other = (SubPartId) o;
return new EqualsBuilder().append(getPartId(), other.getPartId())
.append(getSubPartId(), other.getSubPartId())
.isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder().append(getPartId())
.append(getSubPartId())
.toHashCode();
}
}
}
注意 Part 和 SubPart 映射已被标记为 insertable=false, updateable=false因为映射已在复合主键中定义。Hibernate不允许您使用相同的列映射两个属性,除非您标记 insertable=false、updateable=false。否则你会看到这个很好的例外
应标记为 insertable=false, updateable=false