JPA如何为可嵌入对象提供继承关系

时间:2014-06-30 14:03:17

标签: java hibernate jpa

我有一个抽象类“BaseUnit”来表示我的应用程序中的每个单元。我已将其定义为 @MappedSuperclass

@MappedSuperclass
public class BaseUnit implements UnitMultiplierInterface, Serializable {
/**
 * 
 */
private static final long serialVersionUID = -2648650210129120993L;
@Enumerated(EnumType.STRING)
private UnitMultiplier multiplier;
@Enumerated(EnumType.STRING)
private UnitSymbol unit;
@Column(name = "value")
private double value;

@Override
public void setMultiplier(UnitMultiplier multiplier) {
    this.multiplier = multiplier;
}

@Override
public UnitMultiplier getMultiplier() {
    return multiplier;
}

@Override
public void setUnit(UnitSymbol unit) {
    this.unit = unit;
}

@Override
public UnitSymbol getUnit() {
    return unit;
}

@Override
public void setValue(double currentL1) {
    this.value = currentL1;
}

@Override
public double getValue() {
    return value;
}}

我有一些像Percentage,Resistance这样的子类型。

百分比:我已将其定义为@Embeddable

@Embeddable
public class Percentage extends BaseUnit {
/**
 * 
 */
private static final long serialVersionUID = 2693623337277305483L;

public Percentage() {
    super();
}

public Percentage(double value) {
    setUnit(UnitSymbol.Percentage);
    setValue(value);
}

}

电阻:即可。我已将其定义为@Embeddable

@Embeddable
public class Resistance extends BaseUnit {
/**
 * 
 */
private static final long serialVersionUID = -4171744823025503292L;

public Resistance() {
    super();
}

public Resistance(double value) {
    setUnit(UnitSymbol.Ohm);
    setValue(value);
}

}

我可以在定义实体时使用相同/不同的单位类型。这是一个例子。

@Entity
public class A implements Serializable {
/**
 * 
 */
private static final long serialVersionUID = 5167318523929930442L;
@Id
@GeneratedValue
@Column(name = "id")
private long id;
@Embedded
private Resistance resistance;
@Embedded
/** resistance of scenario. */
private Percentage percentage;

}

现在,我的问题是你认为这个jpa定义可以正常工作吗?或者,您能否告诉我最恰当的方式来达到我的要求?

1 个答案:

答案 0 :(得分:0)

更好的方法是在抽象类中混合@Embeddable@MappedSuperclass,然后以两种不同的方式使用它。如果百分比需要与抵抗相似,那么你根本不需要@MappedSuperClass,但如果不相似,那么下面是你可以达到要求的方式。

@MappedSuperclass
@Embeddable
public class BaseUnit implements Serializable {
...
}

案例1:BaseUnit作为主键

@Entity 
public class AWithResistance implements Serializable {

@EmbeddedId
private BaseUnit key;
....
}

案例2:BaseUnit作为继承公共属性的超类

@Entity 
public class AWithPercentage extends BaseUnit implements Serializable {
....
}
相关问题