Java - Hibernate一个类可以引用多个类中的一个

时间:2017-06-23 07:54:00

标签: java hibernate

我有一个类可以引用多个类中的一个。

旧班的结构如下:

public class CarOne {
    private int id; 
    private int type; //one
    ...
}

public class CarTwo {
    private int id;
    private int type; //two
    ...
}

public class CarThree {
    private int id;
    private int type; //three
    ...
}

它们不是SupperMapped,它们都有自己的ID存在于自己的表中。我没有什么可以改变的,因为它现在已经有很长一段时间了。

现在我需要添加一个新类:

public class Numberplate {
    //here I'd like a one to one mapping to one of the classes?
}

我能想到的一个选择是我可以在汽车对象上添加OneToOne关系,但我希望有一个选项可以使用' id'和'类型'作为将关系置于数字面上的鉴别器。有可能吗?

(免责声明:这些例子纯粹是虚构的,但情况并非如此。)

2 个答案:

答案 0 :(得分:1)

你可以使用联合继承类型,创建一个超类Car然后CarOne,CarTwo,CarThree必须扩展它。您可以找到已加入here

的完整示例

答案 1 :(得分:1)

为什么不使用 TABLE_PER_CLASS 策略?使用此策略,只有具体类在数据库中具有相应的表,而超类仅用于共享和分组目的。

例如,为所有CarClass(CarOne,CarTwo ...)定义一个抽象类,其中包含一个id和type的复合主键。

@Embeddable
public class CarKey implements Serializable{
public Long id;
public String type;
}

在这里,您抽象所有汽车类的父类

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class SuperCar{
@EmbeddedId
public CarKey id;

 // Getter & Setter
}

这里是每个子类的代码

@Entity
public class CarOne extends SuperCar{

// specific attribute
}

这里是您的铭牌类的代码

@Entity
public class Numberplate {

@OneToOne
@JoinColumns({
 @JoinColumn(name="car_id",referencedColumnName = "id"),
 @JoinColumn(name="car_type",referencedColumnName = "type")
})
public SuperCar car;
}

只需处理此策略的性能问题,尤其是如果您有许多子类。