在jpa中一对一地连接复合主键

时间:2018-04-25 06:58:13

标签: hibernate jpa

我有两张桌子。一个是主键,另一个是复合键。

表A:

@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;
}

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;

}

表B:

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

    @EmbeddedId
    private CompositePK compositePK;

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

现在我想实现查询

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

我在TableB中尝试了以下代码段(一对一连接)。

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

但是它说无效列secondaryId。这一天就好了。无法从复合键加入具有主键的表。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

如果是复合,您需要使用复合键对象访问它,如下所示:

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

答案 1 :(得分:0)

您应该修改TableB以使用"派生身份":

@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;
}

在第2.4.1节的JPA 2.1规范中讨论了衍生身份(带有示例)。