有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我有以下表格

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和属性类型object1AttributeValue来填充values实例变量

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

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

但在这种情况下,它也会用类型object2等填充值

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

编辑:我想强调的是,目标是使多个对象(这里Object1Object2ObjectN)没有公共层次结构,但都具有属性的特性。所有对象的属性都将驻留在one表中,通过某种鉴别器进行区分(这里示例为^{


共 (1) 个答案

  1. # 1 楼答案

    我认为目标必须是:

    @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列