gpt4 book ai didi

java - 存储不同类型的列表

转载 作者:行者123 更新时间:2023-11-29 23:01:14 25 4
gpt4 key购买 nike

我有等级车

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 中对上述代码进行建模?

最佳答案

您没有提供足够的详细信息,例如 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 - 存储不同类型的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28480804/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com