[mysql]JPA 休眠到同一个表的两个外键

标签: MySQL Java Hibernate
发布时间: 2017/1/9 21:47:55
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我找到了两个主题这个这个,但仍不能填充它对我的情况。我有 Account 。我可以做 Payments 从一个到另一个帐户。为此目的,我想要存储 payer_account_idreceiver_account_idPayments 表。如何映射,使用注释?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;

    }

解决方法 1:

这似乎是一个一对多关系。如果你想要做双向关系使用这些注释。

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

}

在此代码中我用渴望的回迁,这意味着,如果你有一个对象的帐户,您的列表将自动填充。

希望它能帮助。

赞助商