JPA Hibernate将两个外键放到同一个表中

Ole*_*uts 0 java mysql orm hibernate jpa

我已经找到了两个这个这个主题,但仍然无法填充到我的案例中.我有一个Account.我可以Payments从一个帐户到另一个帐户.出于这个目的,我想存储payer_account_idreceiver_account_idPayments表中.如何使用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;

    }
Run Code Online (Sandbox Code Playgroud)

小智 8

这似乎是一对多的关系.如果要进行双向关系,请使用这些注释.

@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 */

}
Run Code Online (Sandbox Code Playgroud)

在此代码中,我使用EAGER提取,这意味着如果您有一个对象帐户,您的列表将自动填充.

希望能帮助到你.