gpt4 book ai didi

java - Hibernate:如何使用第三个表将属性与条件连接起来

转载 作者:太空宇宙 更新时间:2023-11-04 09:47:29 25 4
gpt4 key购买 nike

我有下表...

Object1
-------
id
...

Object2
-------
id
...

AttributeValue
--------------
id
attribute_id
object_id
value

Attribute
---------
id
name
type

...和实体类

@Entity
@Table(name = "Attribute")
public class Attribute {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;

@Column(name = "name")
private String name;

@Column(name = "type")
private String type;
}


@Entity
@Table(name = "AttributeValue")
public class AttributeValue {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;

@Column(name = "attribute_id")
private Long attributeId;

@Column(name = "object_id")
private Long objectId;

@Column(name = "value")
private String value;
}


@Entity
@Table(name = "Object1")
public class Object1 {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

// ...

// how to annotate to get all matching attribute values?
private Set<AttributeValue> values;
}

我希望 Hibernate 使用具有相应 object_id 和属性类型 object1 的所有 AttributeValue 填充 values 实例变量。

如果只是关于object_id的标准,我会写例如

@JoinColumn(insertable = false, updatable = false, name = "object_id")
private Set<AttributeValue> values;

但在这种情况下,它还会填充类型为 object2 等的值。

所以我的问题是:这种语义可以在 Hibernate 中表达吗?如果可以,如何表达?

编辑:我想强调的是,目标是拥有多个对象(此处为Object1Object2、...ObjectN),这些对象没有共同的层次结构,但都共享具有属性的功能。所有对象的属性将驻留在一个表中,通过某种鉴别器(此处示例为类型)进行区分。

最佳答案

我认为该对象一定是:

@Entity
@Table(name = "AttributeValue")
public class AttributeValue {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;

@Column(name = "attribute_id")
private Long attributeId;

@ManyToOne
    @JoinColumn(name="object_id", nullable=false)
private Object1 object1;

@Column(name = "value")
private String value;
}


@Entity
@Table(name = "Object1")
public class Object1 {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@OneToMany(mappedBy="object1")
private Set<AttributeValue> values;
}

Hibernate 将仅在 AttributeValue 表上生成 object_id 列。

关于java - Hibernate:如何使用第三个表将属性与条件连接起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55240681/

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