我有两个表Part和SubPart。部分表具有一般字段,如id,name,desc等.SubPart表具有part_id,sub_part_id作为复合键。这两个列都引用了Part表,并且每个列都有一对多的映射,就像Part表中的每个part_id一样,SubPart表中的两个列都可以有多个条目。我在定义SubPart表的复合键时遇到问题。我尝试了嵌入式标签,但它不起作用。我该如何解决这个问题。非常感谢。
像这样的部分表。
@Entity
@Table(name="Part")
public class Part {
@Id
@GeneratedValue
@Column(name="Part_Id")
private int id;
@Column(name="Part_Number")
private String partNumber;
@Column(name="Part_Name")
private String partName;
}
子零件表
@Entity
@Table(name="SubPart")
public class SubPart {
// part and subPart combination is the compound key here.
@ManyToOne
@JoinColumn(name="Part_Id")
private Part part;
@ManyToOne
@JoinColumn(name="Sub_Part_Id")
private Part subPart;
@Column(name="Quantity")
private Integer quantity;
}
答案 0 :(得分:6)
你说
我遇到问题为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 因为映射已在复合主键中定义。除非标记为insertable = false,updateable = false,否则Hibernate 不允许您使用相同列映射两个属性。否则你会看到这个很好的异常
应标记为insertable = false,updateable = false
答案 1 :(得分:0)
我想我会声明一个Map< Part,SubPart>类型的字段。在类Part中,并将其声明为@OneToMany。
实际上,在这种特殊情况下,事件可能是Map< Part,Integer>因为唯一的另一个领域是数量。
。不需要SubPart类