用2个外键制作主键

时间:2018-06-21 20:40:56

标签: java hibernate jpa

如何用2个这样的外键制作复合主键?

enter image description here

在我的帐户中执行此操作时:

@Entity
public class Account {
@Id
private int id;
private String number;
private String IBAN;
private String name;

@OneToMany(mappedBy = "account")
private List<Payment> payments = new ArrayList<>();

public List<Payment> getPayments() {
    return payments;
}

public void setPayments(List<Payment> payments) {
    this.payments = payments;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getNumber() {

    return number;
}
...

付款方式:

@Entity
@IdClass(AccountPK.class)
public class Payment {
@Id
private int id;
private Timestamp date;
private float amount;
private String currency;
private String detail;
@Id
private int accountId;
@Id
private int counterAccountId;
private int labelId;

@ManyToOne
private Account account;

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public Timestamp getDate() {
    return date;
}

public void setDate(Timestamp date) {
    this.date = date;
...

我该如何加入?

1 个答案:

答案 0 :(得分:0)

假设id字段不是主键的一部分,则删除其@Id批注。然后像这样注释两个帐户字段:

@Entity
@IdClass(AccountPK.class)
public class Payment {
private int id;
private Timestamp date;
private float amount;
private String currency;
private String detail;
private int labelId;

@Id
@ManyToOne
private Account account;

@Id
@ManyToOne
private Account counterAccount;
...

JPA 2.2 spec第2.4.1节中有类似的例子。