Spring Data JPA,如何将一个属性映射到两列?

Spring Data JPA, how to one attribute map to two columns?

假设我有“帐户”实体 class 和“交易”实体 class。在table中,详细信息是:

transfer_id account_from_id account_to_id money
565 1 2 12
566 3 1 15

那么什么注释或如何编码帐户实体 class,所以当我得到 account.getTransactions 时,对于 account_id = 1,它将有 2 个交易? (因为两个转账实体都涉及account id = 1)

@Entity
@Table
public class Account {
     // ...
     
     //TODO: How should I do here? Use which annotation or how to do?
     private Set<Transfer> transfers;
}

一种可能的解决方案是分别映射“从”和“到”传输:

@Entity
@Table
public class Account {
     @OneToMany
     @JoinColumn(name = "account_from_id")
     private Set<Transfer> fromTransfers;

     @OneToMany
     @JoinColumn(name = "account_to_id")
     private Set<Transfer> toTransfers;
}

但是如果您需要在一个映射集合中同时使用这两种方法,您可以尝试类似的方法:

@Entity
@Table
public class Account {
     @OneToMany
     @JoinFormula("select ts.id from transfer ts where account_from_id = ts.id or account_to_id = ts.id )
     private Set<Transfer> transfers;

}