我有一个抽象类“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;
}}
我有一些子类型,例如百分比、阻力。
百分比:我将其定义为@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 定义可以毫无问题地工作吗?或者您能告诉我实现我的要求的最正确方法吗?
更好的方法是将两者混合@Embeddable
and @MappedSuperclass
在你的抽象类中,然后以两种不同的方式使用它。如果百分比需要与阻力相似,那么你就不需要@MappedSuperClass
完全可以,但如果不相似,那么以下是您可以实现要求的方法。
@MappedSuperclass
@Embeddable
public class BaseUnit implements Serializable {
...
}
情况 1:BaseUnit 作为主键
@Entity
public class AWithResistance implements Serializable {
@EmbeddedId
private BaseUnit key;
....
}
情况2:BaseUnit作为Super Class继承公共属性
@Entity
public class AWithPercentage extends BaseUnit implements Serializable {
....
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)