简体   繁体   中英

Map an entity based on one of two different attributes (either one or the other)

I'm developing a web app using Java, Spring and JPA. The use case I would like to discuss with you is quite simple, it just consists of two entities, Wallet and Transaction . In particular a Wallet can have two kind of transactions, incoming and outgoing . Let's see the structure of these two classes.

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

    ....
}

This is what my code looks like right now, and it works perfectly. My question is, how can I change the code so that instead of having two different lists I would have just one with both incoming and outgoing transactions? So what I would like is something like this:

@Entity
public class Wallet{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long walletId;

    @OneToMany(mappedBy="{'fromWallet' or 'toWallet'}", orphanRemoval = true)
    private List<Transaction> transactions;

    ....
}

Is it possible to do something like this? Or I must stick to the current solution (two different list)?

I don't think the situation you are describing can be achieved with JPA tools, but you can of course do something like

  1. Remodel your database and merge both join columns so that you end up with a "classical" OneToMany relationship with the downside that you lost the information if the wallet was from or to .
  2. Create a getTransactions method in Wallet that simply returns a merged immutable list of outgoingTransactions and incomingTransactions without having the downside of 1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM