我正在使用Java,Spring和JPA开发Web应用程序。我想与您讨论的用例非常简单,它仅由两个实体Wallet
和Transaction
组成。特别是Wallet
可以有两种交易,incoming和outgoing。让我们看看这两个类的结构。
@Entity
public class Wallet{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long walletId;
@OneToMany(mappedBy="fromWallet", orphanRemoval = true)
private List<Transaction> outgoingTransactions;
@OneToMany(mappedBy="toWallet", orphanRemoval = true)
private List<Transaction> incomingTransactions;
....
}
public class Transaction{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long transactionId;
@ManyToOne
@JoinColumn(name = "wallet_id_from")
private Wallet fromWallet;
@ManyToOne
@JoinColumn(name = "to_wallet_id")
private Wallet toWallet;
....
}
这就是我的代码现在的样子,它可以完美运行。我的问题是,我该如何更改代码,这样就不会有两个不同的列表,而只有一个包含传入和传出事务的列表?所以我想要的是这样的:
@Entity
public class Wallet{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long walletId;
@OneToMany(mappedBy="{'fromWallet' or 'toWallet'}", orphanRemoval = true)
private List<Transaction> transactions;
....
}
是否可以做这样的事情?还是我必须坚持当前的解决方案(两个不同的列表)?
我认为您描述的情况无法通过JPA工具实现,但您当然可以做类似的事情
OneToMany
关系,而如果钱包是from
或to
,则丢失了信息。getTransactions
中创建一个Wallet
方法,该方法仅返回outgoingTransactions
和incomingTransactions
的合并的不可变列表,而没有缺点1。