18

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?

Mr. Alien
  • 153,751
  • 34
  • 298
  • 278
Marcus
  • 527
  • 1
  • 6
  • 23

1 Answers1

35

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;
}
Perception
  • 79,279
  • 19
  • 185
  • 195
  • 1
    And if there's multiple secondary tables? In my case, the object is a main object with several other tables that are referenced. In some cases, the object creation is necessary, in others, the @ElementCollection works. But I was curious if there was another solution for a single column (like retrieving a description field for a code/description table). – Marcus Mar 19 '13 at 15:30
  • 6
    If you have multiple secondary tables then use ... [`@SecondaryTables`](http://docs.oracle.com/javaee/6/api/javax/persistence/SecondaryTables.html) – Perception Mar 19 '13 at 15:31
  • 4
    @Perception: shouldn't it be `@Column(table="other_table", name="barCode")` ? Are you exploiting [this](http://stackoverflow.com/a/19454829/1654265) implicitly, is it a typo, or is there some other name conversion elsewhere ? – Andrea Ligios Sep 18 '15 at 13:29
  • 1
    What if I have a ManyToOne relationship between Foo and a Bar and still wants to access as a property of class Foo but that value is actually of a Bar, although I have specified Bar with a foreign key association (ManyToOne) in Foo ? – Harsh Vardhan Ladha Sep 19 '16 at 05:19