已经涵盖了类似的主题,但没有在表中使用复合键的问题。 基本上我试图从单个表中获取层次结构树,其具有以下结构:
我的目标是使用hibernate注释将单个类映射到此表,然后从中构建我的层次结构树:
@Entity
@Table(name = "Enti")
public class DevUnit {
/** The valuable fields from the Enti table */
// Primary Key (PK) Object
@EmbeddedId
@AttributeOverrides({
@AttributeOverride(name = "stazione", column = @Column(name="IdStazione")),
@AttributeOverride(name = "categoria", column = @Column(name="IdCategoria")),
@AttributeOverride(name = "tipoente", column = @Column(name="IdTipoEnte")),
@AttributeOverride(name = "ente", column = @Column(name="IdEnte"))
})
private EnteDBPK EnteDBPK;
@OneToMany
@JoinColumn(name = "parentId")
private List<DevUnit> children = new ArrayList<DevUnit>();
@ManyToOne(targetEntity = DevUnit.class, optional=true, fetch=FetchType.LAZY)
@JoinColumn(name = "parenId",insertable=false,updatable=false)
private DevUnit parent = null;
// Getters and setters...
}
EnteDBPK是我的复合键,定义为:
@Embeddable
public class EnteDBPK implements Serializable {
private static final long serialVersionUID = 2960251547408481498L;
/** Fields representing the composite primary key*/
private long stazione;
private long categoria;
private long tipoente;
private long ente;
public EnteDBPK(){}
public EnteDBPK(long stazione, long categoria, long tipoente, long ente){
this.stazione = stazione;
this.categoria = categoria;
this.tipoente = tipoente;
this.ente = ente;
}
// Getters and setters, equals and hashcode overrides...
}
可能没有正确定义关联,因为当我尝试运行它时出现此错误:
org.hibernate.AnnotationException: A Foreign key refering package.DevUnit from package.DevUnit has the wrong number of column. should be 4
我确信我在两个协会中都缺少某些内容,但我需要你的帮助才能理解问题并找到解决方案。
感谢您的帮助。
安东尼奥
答案 0 :(得分:0)
如果DevUnit
的复合键由4列组成,则引用它的外键也应包含4列:
@OneToMany(mappedBy = "parent")
private List<DevUnit> children = new ArrayList<DevUnit>();
@ManyToOne(optional=true, fetch=FetchType.LAZY)
@JoinColumns({
@JoinColumn(name = "parentIdStazione", referencedColumnName = "IdStazione"),
@JoinColumn(name = "parentIdCategoria", referencedColumnName = "IdCategoria"),
@JoinColumn(name = "parentIdTipoEnte", referencedColumnName = "IdTipoEnte"),
@JoinColumn(name = "parentIdEnte", referencedColumnName = "IdEnte")
})
private DevUnit parent = null;
实际上,如果默认名称没问题,你可以省略@JoinColumns
。
另请注意,Hibernate文档不推荐您映射双向一对多/多对一关系(“一方”是拥有方)的方法,因此我在代码段中使用了另一种方法上面,请参阅2.2.5.3.1.1. Bidirectional。