这个问题对我来说很难制定。随时询问是否需要澄清。嵌入式类和双向关系
情况:我有一个使用Hibernate的Spring应用程序在数据库中保存不同的实体类。为简化调用这些类E1, E2, .., E20
。所有这些类都基于相同的摘要@MappedSuperclass
,但没有真正的继承(在数据库方面)。
现在我想添加新的实体类(En1, En2, ...
)并建立双向关系到一些现有的实体。假设En1
与E1,E2,E3
一个维吾尔,我的代码看起来是这样的:
@Entity
public class E1 extends SuperClass {
//other attributes
@OneToMany(mappedBy = "e1")
List<En1> newAttribut;
public En1 doMagic(En1 entity) {
//a long function which does somthing with the entity
}
//other attribute
}
//-----------------------------//
// The same code for E2 and E3 //
//-----------------------------//
@Entity
public class En1 {
//other attributes
@ManyToOne
E1 e1;
@ManyToOne
E2 e2;
@ManyToOne
E3 e3;
//other attributes
}
问题:该解决方案适用不舒服。我需要为每个关系在类En1
中指定一个属性,并且必须在每个现有实体中复制doMagic()
方法。此外,在实践中,实体En1
将一次只与另一个实体有关系。因此三个属性中的两个将是null
。
试图解决方案:的@Embeddable
的使用解决了重新实现相同的代码的问题E1,..,E3
public class EmbeddedEn1 implements Serializable {
@OneToMany(mappedBy="parentEntity")
private List<En1> newAttribut;
public En1 doMagic(En1 entity) {
//a long function which does somthing with the new entity
}
}
但不能建立在"parentEntity"
双diretion。
继承不工作:当然,我可以用一类像hasAttributEn1
从E1,E2,E3
继承,但这并不与其他新实体 - 类扩展。假设下面的情况,其中新的实体En2,..,En4
应该是相对于以下实体:
En2 <-> E1, E3
En3 <-> E2,E3
En4 <-> E1,E2
在这种情况下,就需要多继承。
任何建议如何解决这个问题,而无需重复的代码?
我在我的项目中使用通用DAO。但是这个问题对应于模型结构,即实体的设计,而不是我可以访问它们的方式。 – Thanthla