JPA休眠两个指向同一个表的外键 [英] JPA Hibernate two foreign keys to the same table

查看:160
本文介绍了JPA休眠两个指向同一个表的外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到了两个主题,但仍然无法将其填充到我的情况下.我有一个Account.我可以从一个帐户到另一个帐户执行Payments.为此,我想将payer_account_idreceiver_account_id存储在Payments表中.如何使用注释映射它?

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;

    }

推荐答案

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

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

}

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

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

希望有帮助.

这篇关于JPA休眠两个指向同一个表的外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆