Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 401
Marcus Avatar asked Mar 19 '13 15:03

Marcus


People also ask

Which of the following annotation is used in JPA to link two tables through a relation table?

@ManyToMany associations Most often, you will need to use @JoinTable annotation to specify the mapping of a many-to-many table relationship: the name of the link table and. the two Foreign Key columns.

How do I map one table to another table in hibernate?

You need to annotate each attribute which you want to map to the secondary table with a @Column annotation and set the name of the secondary table as the value of the table attribute.


1 Answers

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;
}
like image 183
Perception Avatar answered Oct 12 '22 14:10

Perception