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

时间:2015-09-21 14:50:36

标签: java mysql hibernate jpa orm

我发现了两个主题thisthis,但仍无法填充到我的案例中。我有Account。我可以从一个帐户到另一个帐户Payments。为此,我希望将payer_account_idreceiver_account_id存储在Payments表中。如何使用Annotations进行映射? enter image description here

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

    }

2 个答案:

答案 0 :(得分:7)

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

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

}

在此代码中,我使用EAGER提取,这意味着如果您有对象帐户,系统会自动填充您的列表。

希望它有所帮助。

答案 1 :(得分:0)

如何?

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


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