我知道@Embeddable
不支持 Hibernate 中的组件继承,我正在尝试找到处理我非常自定义的实体映射的最佳策略。
故事如下:
我有两张桌子:
prices_a_b
和prices_a_b_c
我有两个实体映射到它们:
PriceAB
和PriceABC
这两个表都只有复合 PK,它
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
你们认为哪种策略最适合?
提前致谢!