基于两个不同属性(一个或另一个)的一个属性映射实体

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

我正在使用Java,Spring和JPA开发Web应用程序。我想与您讨论的用例非常简单,它仅由两个实体WalletTransaction组成。特别是Wallet可以有两种交易,incomingoutgoing。让我们看看这两个类的结构。

@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;

    ....
}

是否可以做这样的事情?还是我必须坚持当前的解决方案(两个不同的列表)?

java hibernate jpa hibernate-mapping
1个回答
0
投票

我认为您描述的情况无法通过JPA工具实现,但您当然可以做类似的事情

  1. [重塑数据库并合并两个连接列,使您最终获得“经典” OneToMany关系,而如果钱包是fromto,则丢失了信息。
  2. getTransactions中创建一个Wallet方法,该方法仅返回outgoingTransactionsincomingTransactions的合并的不可变列表,而没有缺点1。
© www.soinside.com 2019 - 2024. All rights reserved.