来自同一实体的多个外键? (JPA休眠)
问题描述:
我有两个实体,一个Customer和一个CustomerTransaction。我希望能够将CustomerTransaction中的两个Customer ID存储为外键(一个用于发起交易的客户,另一个用于客户接收)。我还希望每个Customer对象都包含它们链接到的所有CustomerTransaction的列表。来自同一实体的多个外键? (JPA休眠)
Customer.java
@Entity
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String firstName;
private String lastName;
//@ManyToOne ?
private List<CustomerTransaction> customerTransaction;
//getters and setters
}
CustomerTransaction.java
@Entity
public class CustomerTransaction {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
//@OneToMany ?
private Customer initiater;
//@OneToMany ?
private Customer receiver;
private String transactionDetails;
//getters and setters
}
如何设置了JPA注解,使每一笔交易包含客户发起和接收的外键ID?
答
initiater
和receiver
需要注解ManyToOne
(许多交易是由一个启动者发起的)。
而且你需要在:一个用于启动tranactions(OneToMany(mappedBy = "initiater")
),以及一个用于接收交易:(OneToMany(mappedBy = "receiver")
你不能只是一个列表(而且它可能不希望反正)。
谢谢你的帮助! – DraegerMTN