JPA Annotations - How to retrieve a single value from a different table than the current object?

丶灬走出姿态 提交于 2019-12-20 12:03:31

问题


How do you map a single value from a column in another table to the current object?

Example:

class Foo {
    @Id
    @Column(name="FOO_ID")
    private String fooId;

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

    //Column to map to another table?
    //is a one to one mapping - but don't want a separate object for this.
    private String barCode;
}

Table: Fields

Foo: FOO_ID, FOO_A

Bar: FOO_ID, BAR_CODE

How do I retrieve the BAR_CODE field without creating a separate object (or a secondary table) using JPA annotations?


回答1:


Use a secondary table. This allows you to map for an entity, on a one-to-one basis, another table and define column mappings that use it.

Example:

@Entity
@Table(name = "foo")
@SecondaryTable(name = "other_table", pkJoinColumns=@PrimaryKeyJoinColumn(name="id", referencedColumnName="FOO_ID"))
public class Foo {
    @Id
    @Column(name="FOO_ID")
    private String fooId;

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

    @Column(table="OtherTable", name="barCode")
    private String barCode;
}


来源:https://stackoverflow.com/questions/15503189/jpa-annotations-how-to-retrieve-a-single-value-from-a-different-table-than-the

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!