开发者

Retrieve Collection of Subclasses Based on Column Value

The title is a bit weird, so let me clarify.

I have two objects, Garage and Vehicle, in a one-to-many relationship. There are multiple types of vehicles, such as car and truck; the type is persisted as a string in the Vehicle table.

Here's the two classes:

@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;

    ....
}

In order to differentiate between types of Vehicles, currently we have to look at the type column and use an enum. What I'd like to do is have subclasses of Vehicle, such are Car and Truck, to represent the different types rather than relying on the Type field. Then my code can instanceof to determine the type instead of using that field.

However, I don't know how to tell Hibernate how to ins开发者_如何转开发tantiate subclasses based on the value of the Type column, or if it even can.

I'd appreciate any help you guys can give. Thanks in advance!


If you want to save the current database schema, you need to use SINGLE_TABLE inheritence strategy with type column as a discriminator:

@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 { ... }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜