我上课车

Class Car{
    protected List<Attribute> attributes;
}


然后我们有Attribute类

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


如何在休眠状态下对上述代码建模?

最佳答案

您没有提供足够的详细信息,因为CarAttribute(一对多或多对多)之间的确切关系是什么,您想对Attribute使用哪种继承策略(单表,课),但这应该可以帮助您入门

@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)的两个关系,这将需要Attribute实体中的两个AttributeOption类型的字段,或者(对于我的示例而言)每个关系的单独联接表。

请注意,这是我直接在答案中键入的,因此可能存在错误。

关于java - 储存不同类型的 list ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28480804/

10-13 05:26