我有班车
Class Car{
protected List<Attribute> attributes;
}
然后我们有类属性
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中对上面的代码进行建模?
答案 0 :(得分:0)
您没有提供足够的详细信息,因为Car
和Attribute
(一对多,或多对多)之间的确切关系是什么,您要将哪种继承策略用于{{ 1}}(单个表,每个类的表),但这应该让你开始
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
...
}
和startRange
)的两个关系,它们需要endRange
实体中两个Attribute
类型的字段,或者(在我的例子中)每个关系的单独连接表。
请注意,我直接在答案中输入了这个内容,因此可能存在错误。