JPA Hibernate two foreign keys to the same table

我只是一个虾纸丫 提交于 2020-01-25 20:29:46

问题


I've found two topics this and this, but still cannot populate it to my case. I have an Account. I can do Payments from one account to another. For that purpose I want to store payer_account_id and receiver_account_id in Payments table. How can I map that using Annotations?

@Entity
public class Account {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private Double balance;

    //mapping here to Payments Entity
    private ???

}


@Entity
    public class Payments {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
         private Long id;
        private Double ammount;

        //mapping here to Account Entity
        private Account payerAccount;

        //mapping here to Account Entity
        private Account receiverAccount;

    }

回答1:


It seems to be an one-to-many relations. If you want to do a bidirectional relations use these annotations.

@Entity
public class Account {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private Double balance;

    @OneToMany(mappedBy="payerAccount", fetch = FetchType.EAGER)
    private Collection<Payments> payers;

    @OneToMany(mappedBy="receiverAccount", fetch = FetchType.EAGER)
    private Collection<Payments> receivers;


    /* GETTERS AND SETTERS */
}

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

    private Double ammount;

    @ManyToOne
    @JoinColumn(name="payer_account_id")
    private Account payerAccount;

    @ManyToOne
    @JoinColumn(name="recever_account_id")
    private Account receiverAccount;

    /* GETTERS AND SETTERS */

}

In this code i use EAGER fetch, it means that your lists will be automatically populated if you have an object account.

Hope it helps.




回答2:


How about this:

    //mapping here to Account Entity
    @ManyToOne  
    private Account payerAccount;


    //mapping here to Account Entity
    @ManyToOne
    private Account receiverAccount;


来源:https://stackoverflow.com/questions/32698294/jpa-hibernate-two-foreign-keys-to-the-same-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!