使用组合键的单个字段进行JPA连接

时间:2020-07-17 08:19:27

标签: hibernate jpa spring-data-jpa

我有两个表,其中一个(书本)有一个复合键。另一个表Author引用了Book中的bId列。可以在JPA中加入吗?

<ListView 
    ItemsSource="{Binding CustomList}"
    SelectedItem="{Binding CustomSelectedItemProperty, Mode=TwoWay}"
</ListView>

T1-图书

@Embeddable
public class T1Id implements Serializable {

private String bId;
private String name;
private String country;
}

T2-作者

@Entity
@Table(name= "book")
public class Book implements Serializable {

@EmbeddedId
private T1Id id;

@OneToMany(fetch = EAGER, cascade = ALL, mappedBy = "book")
private Set<Author> authors = new HashSet<>();
}

如果我在“加入”条件中添加“书籍”中的其他列,则会出现错误,因为“地址实体”没有这些列。如果我尝试使用上述方法加入,则会错误地指出列数是错误的

Entity
@Table(name = "Author")
public class Author implements Serializable {

private String bId;

private String address;

@ManyToOne
@JoinColumn(name = "bId", referencedColumnName="bId", insertable = false, updatable = false)
private Book book;
}

1 个答案:

答案 0 :(得分:0)

使用referencedColumnName="bId"指定列

@ManyToOne
@JoinColumn(name = "bId", referencedColumnName="bId", insertable = false, updatable = false)
private Book book;

或使用@MapsId

@MapsId("bId")
@ManyToOne
@JoinColumn(name = "bId", insertable = false, updatable = false)
private Book book;