【问题标题】:Spring Data JPA, how to one attribute map to two columns?Spring Data JPA,如何将一个属性映射到两列?
【发布时间】:2021-07-26 09:22:16
【问题描述】:

假设我有“Account”实体类和“Transaction”实体类。在表中,详细信息为:

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

那么什么注解或者如何编码Account实体类,所以当我得到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;
}

【问题讨论】:

    标签: spring hibernate spring-data-jpa hsqldb


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-01
      • 2021-09-15
      • 1970-01-01
      • 2021-04-02
      • 2020-02-29
      • 1970-01-01
      相关资源
      最近更新 更多