标题有点奇怪,让我澄清一下。
我有两个对象,车库和车辆,处于一对多关系。车辆有多种类型,例如轿车和卡车;该类型作为字符串保留在车辆表中。
这是两个类:
@Entity
@Table(...)
public class Garage {
....
@Column(name = "garageId")
private Integer garageId;
@OneToMany
@JoinColumn(name = "garageId")
private Set<Vehicle> vehicles;
....
}
@Entity
@Table(...)
public class Vehicle {
....
@Column(name = "garageId")
private Integer garageId;
//could be "Truck" or "Car"
@Column(name = "type")
private String type;
....
}
为了区分车辆的类型,目前我们必须查看类型列并使用枚举。我想做的是拥有 Vehicle 的子类(例如 Car 和 Truck)来表示不同的类型,而不是依赖于 Type 字段。然后我的代码可以 instanceof
来确定类型,而不是使用该字段。
但是,我不知道如何告诉 Hibernate 如何根据 Type 列的值实例化子类,或者甚至不知道它是否可以。
我很感激你们能提供的任何帮助。提前致谢!
最佳答案
如果要保存当前数据库架构,则需要使用 SINGLE_TABLE
继承策略,并以 type
列作为区分符:
@Entity
@Table(...)
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type")
public abstract class Vehicle { ... }
@Entity
@DiscriminatorValue("...")
public class Car extends Vehicle { ... }
@Entity
@DiscriminatorValue("...")
public class Truck extends Vehicle { ... }
关于java - 根据列值检索子类的集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4149268/