简体   繁体   English

Hibernate映射来自同一表的列值的集合

[英]Hibernate mapping of collection of a column value from the same table

Given the following table: 给出下表:

CREATE TABLE MY_SCHEMA.TABLE_A (
    id integer NOT NULL,
    value character varying(50) NOT NULL,
    linked_id integer
)

I want to know the hibernate annotations to complete my entity class: 我想知道休眠注释来完成我的实体类:

public class TableA {
    @Id @Column(name="id", unique=true)
    private int id;
    @Column(name="value", nullable=false)
    private String value;
    // missing annotations
    private String linkedValue;
}

So that I get the linkedValue (which comes from a self join to TABLE_A on linked_id = id and select from the column value ) as String in my entity class TableA . 这样一来,我在实体类TableA获得了linkedValue (作为对linked_id = id TABLE_A的自连接,并从列value选择)作为String的形式。

Similarly, in case it is not one-to-one: 同样,如果不是一对一的:

CREATE TABLE MY_SCHEMA.TABLE_A (
    id integer NOT NULL,
    value character varying(50) NOT NULL
)

CREATE TABLE MY_SCHEMA.TABLE_B (
    table_a_id integer NOT NULL,
    linked_table_a_id integer NOT NULL
)

What are the hibernate annotations to complete my entity class: 什么是休眠注释来完成我的实体类:

public class TableA {
    @Id @Column(name="id", unique=true)
    private int id;
    @Column(name="value", nullable=false)
    private String value;
    // missing annotations
    private Set<String> linkedValues;
}

So that I get the set of linkedValues (which comes from joining TABLE_A to TABLE_B on id = table_a_id and joining TABLE_A again on linked_table_a_id = id to select from the column value ) in my entity class TableA . 所以,我得到了一套linkedValues (这来自加盟TABLE_ATABLE_Bid = table_a_id和加入TABLE_A再次linked_table_a_id = id从列中选择value在我的实体类) TableA

Prefer answers without needing to introduce and extra entity class TableB . 无需引入额外的实体类TableB即可选择答案。 Thank you. 谢谢。

You can use JPA 2.0 's @ElementCollection : 您可以使用JPA 2.0的@ElementCollection

public class TableA {

   @Id @Column(name="id", unique=true)
   private int id;

   @Column(name="value", nullable=false)
   private String value;

    @ElementCollection
    @CollectionTable(name = "TABLE_A",joinColumns = @JoinColumn(name = "linked_id"))
    @Column(name = "value")
    private Set<String> linkedValues = new HashSet<String>();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM