user3016222
user3016222

Reputation: 71

one to one join on composite primary key in jpa

I have two tables. One is having primary key and another one is having composite key.

TableA:

@Entity
@Table(name = "TableA")
public class TableA {

    @Id
    @Column(name = "myId")
    private Long id;

    @Column(name = "myName")
    private String name;

    @Column(name = "myRegion")
    private String regionName;
}

Composite key for TableB:

@Embeddable
public class CompositePK implements Serializable {

    private static final long serialVersionUID = 1L;

    @Column(name = "myId", insertable=false, updatable=false)
    private Long myId;

    @Column(name = "secondaryId")
    private String secondaryId;

}

TableB:

@Entity
@Table(name = "TableB")
public class TableB {

    @EmbeddedId
    private CompositePK compositePK;

    @Column(name = "Data")
    private String regulationText;
}

Now I want to implement the query

select * from TableA tableA 
        inner join TableB tableB 
        on tableA.myId=tableB.myId
        where tableB.myId = 1;

I have tried the below snippet in TableB (one to one join).

@OneToOne(cascade = CascadeType.ALL)
    @JoinTable(name = "TableA", inverseJoinColumns = @JoinColumn(name = "myId", referencedColumnName = "myId"))
    private TableA tableA;

But it says that Invalid column secondaryId. Figthing with this for a day. Unable to join a table with primary key from composite key. Any help will be appreciated.

Upvotes: 0

Views: 1737

Answers (2)

Brian Vosburgh
Brian Vosburgh

Reputation: 3276

You should modify TableB to use "derived identity":

@Entity
@Table(name = "TableB")
public class TableB {

    @EmbeddedId
    private CompositePK compositePK;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "myId", referencedColumnName = "myId")
    @MapsId("myId") // maps 'myId' attribute of embedded id CompositePK
    private TableA tableA;

    @Column(name = "Data")
    private String regulationText;
}

Derived identities are discussed (with examples) in the JPA 2.1 spec in section 2.4.1.

Upvotes: 1

Ishant Gaurav
Ishant Gaurav

Reputation: 1203

In case of composite you need to access it with the composite key object like as below :

 @OneToOne(cascade = CascadeType.ALL)
 @JoinTable(name = "TableA", inverseJoinColumns = @JoinColumn(name = 
 "compositePK.myId", referencedColumnName = "myId"))
 private TableA tableA;

Upvotes: 0

Related Questions