我知道 @Embeddable
不支持 Hibernate 中的组件继承,我试图找到处理我非常自定义的实体映射的最佳策略。
故事如下:
prices_a_b
和 prices_a_b_c
PriceAB
和 PriceABC
prices_a_b_c
向 PK 因此,这将是程序化翻译:
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class Price implements Serializable {
@EmbeddedId
private AbstractPricePk id;
public AbstractPricePk getId() {
return id;
}
}
@Entity
@Table(name = "price_a_b")
@AssociationOverrides(
{
@AssociationOverride(name = "id.a", joinColumns = @JoinColumn(name = "a")),
@AssociationOverride(name = "id.b", joinColumns = @JoinColumn(name = "b"))
}
)
public class PriceAB extends Price {
private PriceABPk id;
protected PriceAB() {}
public PriceAB(PriceABPk id) {
this.id = id;
}
@Override
@EmbeddedId
public PriceABPk getId() {
return id;
}
}
@Entity
@Table(name = "price_a_b_c")
@AssociationOverrides(
{
@AssociationOverride(name = "id.a", joinColumns = @JoinColumn(name = "a")),
@AssociationOverride(name = "id.b", joinColumns = @JoinColumn(name = "b")),
@AssociationOverride(name = "id.c", joinColumns = @JoinColumn(name = "c"))
}
)
public class PriceABC extends Price {
private PriceABCPk id;
protected PriceABC() {}
public PriceABC(PriceABCPk id) {
this.id = id;
}
@Override
@EmbeddedId
public PriceABCPk getId() {
return id;
}
}
这是PKs模型:
public interface PricePk extends Serializable {
public A getA();
public B getB();
}
@MappedSuperclass
public abstract class AbstractPricePk implements PricePK {
@ManyToOne
@JoinColumn(name = "a")
private A a;
@ManyToOne
@JoinColumn(name = "b")
private B b;
protected AbstractPricePK() { }
public AbstractPricePK(A a, B b) {
this.a = a;
this.b = b;
}
public A getA() {
return this.a;
}
public void setA(A a) {
this.a = a;
}
public B getB() {
return b;
}
public void setB(B b) {
this.b = b;
}
}
@Embeddable
public class PriceABPk extends AbstractPricePk {
public PriceABk(A a, B b) {
super(a,b);
}
}
@Embeddable
public class PriceABCPk extends AbstractPricePk {
@ManyToOne
private C c;
public PriceABCPk(A a, B b, C c) {
super(a, b);
this.c = c;
}
public C getC() {
return b;
}
public void setC(C c) {
this.c = c;
}
}
我得到的错误:
org.hibernate.AnnotationException: PriceABPk must not have @Id properties when used as an @EmbeddedId: PriceAB.id
现在,这一切背后的想法是我想要一个
PriceService
可以查询两个表并返回 Price
目的。稍后,如果我需要检索 C
来自 PriceABC
我可以做一个 instanceof
,但大多数时候我需要对两种类型的 Price
执行相同的操作对象。同样,我想要一个 PriceDao
这将创建 Price
对象取决于我作为参数传递的对象。你们认为哪种策略最适合?
提前致谢!
最佳答案
您可以通过在 @EmbeddedId 中用组合替换继承来进行“黑客攻击”
@Table (name="prices_a_b")
public class PriceAB extends Price {
@EmbeddedId
private PriceABId id;
// getters/setters etc.
}
@Table (name="prices_a_b_c")
public class PriceABC extends Price {
@EmbeddedId
private PriceABCId id;
@Embeddable
class PriceABCId implements Serializable {
private PriceABId id;
@Column(name="COLUMN_C")
private C additionalPkPropertyC;
}
}
@MappedSuperclass
public abstract class Price {
//all common properties go here
}
关于Hibernate/JPA 2.0 - 每个类的表和@EmbeddedId 继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16606474/