JPA - 让 2 列引用不同表中的同一列

问题描述 投票:0回答:1

Spring boot JPA 新手在这里。我有一个如下所示的

Account
实体

@Entity
public class Account {

@Id
@GeneratedValue
private Long accNo;

private Double balance = 0.0;

@ManyToOne
@JoinColumn(name = "username")
private UserInfo userInfo;

我有一个

Transaction
实体如下:

@Entity
public class Transaction {

@Id
@GeneratedValue(strategy = GenerationType.UUID)
private UUID transactionID;

@ManyToOne
@JoinColumn(name = "fromAccount")
private Account fromAccount;

@ManyToOne
@JoinColumn(name = "toAccount")
private Account toAccount;

private Double amount;

private Double balance;

@Column(columnDefinition = "TIMESTAMP WITH TIME ZONE")
private OffsetDateTime timestamp;

我想确保

fromAccount
toAccount
始终是
accNo
中有效的
Account

我尝试使用下面的方法,但出现编译错误。

@Id
@GeneratedValue
@OneToMany(mappedBy = "fromAccount")
@OneToMany(mappedBy = "toAccount")
private Long accNo;

我可以看到它可以在 PostgreSql 中完成,但如何在 JPA 中做到这一点?非常感谢任何建议。

postgresql spring-boot jpa spring-data-jpa
1个回答
0
投票

您需要使用两个

oneToMany
与事务实体的关系来实现双向关系。

@OneToMany(mappedBy="fromAccount")
private Collection<Transaction> fromAcc;

@OneToMany(mappedBy="toAccount")
private Collection<Transaction> toAcc;
© www.soinside.com 2019 - 2024. All rights reserved.