存储不同类型的列表

Storing List of different types

我有class辆车

Class Car{
    protected List<Attribute> attributes;
}

然后我们有class属性

Class Attribute{
    protected String name;
    protected int sortOrder;
}

那么我们就有了三种属性

// single class represents Dropdown
class Single extends Attribute{
    protected List<AttributeOption> options;
}

// multiple class represents Checkbox
class Multiple extends Attribute{
    protected List<AttributeOption> options;
}

class Range extends Attribute{
    protected List<AttributeOption> startRange;
    protected List<AttributeOption> endRange;
}

class AttributeOption{
    protected String name;
    protected int sortOrder;
}

如何在 hibernate 中对上述代码进行建模?

你没有给出足够的细节,因为 CarAttribute 之间的确切关系是什么(一对多,或多对多),你想使用哪种继承策略Attribute(单个 table,每个 class table),但这应该让你开始

@Entity
public class Car {
    ...
    @OneToMany(mappedBy = "car")
    private List<Attribute> attributes;
    ...
    // getters, setters
}

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public abstract class Attribute {
    ...
    private String name;
    private Integer sortOrder;
    @ManyToOne
    @JoinColumn(name = "car_id")
    private Car car;
    ...
    // getters, setters
}

@Entity
public class Single extends Attribute {
    ...
    @OneToMany(mappedBy = "attribute")
    private List<AttributeOption> options;
    // getters, setters
    ...
}

@Entity
public class Multiple extends Attribute {
    ...
    @OneToMany(mappedBy = "attribute")
    private List<AttributeOption> options;
    // getters, setters
    ...
}

@Entity
public class Range extends Attribute {
    ...
    @OneToMany(mappedBy = "attribute")
    @JoinTable(name = "startrange_option", 
               joinColumns = @JoinColumn(name = "range_id"), 
               inverseJoinColumns = @JoinColumn(name = "option_id")
    private List<AttributeOption> startRange;
    @OneToMany(mappedBy = "attribute")
    @JoinTable(name = "endrange_option", 
               joinColumns = @JoinColumn(name = "range_id"), 
               inverseJoinColumns = @JoinColumn(name = "option_id")
    private List<AttributeOption> endRange;
    ...
}

@Entity
public class AttributeOption {
    ... 
    private String name;
    private Integer sortOrder
    @ManyToOne
    @JoinColumn(name = "attribute_id")
    private Attribute attribute;
    // getters, setters
    ...
}

棘手的部分是与同一实体的两个关系(startRangeendRange),这将需要 AttributeOption 实体中的两个 Attribute 类型的字段,或者(如我的示例)为每个关系单独加入 tables。

请注意,这是我直接在答案中输入的,所以可能有错误。