简体   繁体   English

多列的 Hibernate MappedBy

[英]Hibernate MappedBy for Multiple columns

I am using Postgresql for my database and it contains a table called user and a table called friendship, which has 2 foreign keys userA_id and userB_id.我在我的数据库中使用 Postgresql,它包含一个名为 user 的表和一个名为 Friends 的表,它有 2 个外键 userA_id 和 userB_id。 I know how to use mappedBy to check for friendships based on userA_id but I am not sure how to check for userB_id.我知道如何使用mappedBy 根据userA_id 检查好友关系,但我不确定如何检查userB_id。 Is there a way to tell hibernate to check a user ID from user table with both of columns on friendship table?有没有办法告诉 hibernate 从用户表中检查用户 ID 与友谊表上的两列?
在此处输入图片说明

EDIT: Here is the code I currently have.编辑:这是我目前拥有的代码。

@Entity
@Table(name = "users")
public class UserDB implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "userid", nullable=false)
    public int userID; //not null

    @OneToMany (targetEntity = FriendshipDB.class, mappedBy = "userA_ID", cascade = CascadeType.ALL, fetch=FetchType.EAGER)
    //@OneToMany (targetEntity = FriendshipDB.class, mappedBy = "userB_ID", cascade = CascadeType.ALL, fetch=FetchType.EAGER)
    public List<FriendshipDB> friends = new ArrayList<>();
}

@Entity
@Table(name = "friendships")
public class FriendshipDB implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "friendshipid", nullable = false)
    private int friendshipID; //not null

    @ManyToOne
    @JoinColumn(name="usera_id")
    private UserDB userA_ID; //not null

    @ManyToOne
    @JoinColumn(name = "userB_id")
    private UserDB userB_ID;
}

I think this is very specific mapping but the only solution I know is to go with 2 association like this:我认为这是非常具体的映射,但我知道的唯一解决方案是使用这样的 2 个关联:

@OneToMany(mappedBy = "user1")
private Collection<User> usersByFirst;
@OneToMany(mappedBy = "user2")
private Collection<User> usersBySecond;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM