Search code examples
springhibernatespring-data-jpahsqldb

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


Suppose I have "Account" entity class, and "Transaction" entity class. In table, detail is:

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

So what annotation or how to code Account entity class, so when I get account.getTransactions, for account_id = 1, it will has 2 transactions? (because both transfer entity involves 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;
}

Solution

  • One possible solution is to map "from" and "to" transfers separately:

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

    But if you need both in one mapped collection you can try something like:

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