使用来自相同表的两个外键进行休眠 - 注释 [英] Hibernate with two foreign keys from same table- annotation

查看:102
本文介绍了使用来自相同表的两个外键进行休眠 - 注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想设计一个好客的应用程序。我有两个表 User Request 。用户可以主机访问者,并可以向对方发送主机请求。但没有必要将用户定义为访客或主机,这对系统没有影响,所以我没有为他们分开的表。此差异在请求表中非常重要,需要将 visitor_id host_id 保留为外键(映射为 user_id 用户表中的主键列,因为主机和访问者都是用户)。

I'm trying to design a hospitality app. I have two tables as User and Request. Users could be Host or Visitor and can send host request to each other. but there is no need to define Users as visitor or host, it doesn't matter for the system so I don't have seperate tables for them. This difference is just important in Request table and it's needed to keep visitor_id and host_id as foreign keys (mapped with user_id primary key column from User table because both host and visitor are also User).

我的问题是如何定义这个关系在hibernate中用 Annotation ?我的意思是,在请求表中应该有两个外键,它们被映射到User表中的* user_id *主键列。

My question is how can I define this relation in hibernate with Annotation? I mean, there should be two foreign keys in Request table and they're mapped to *user_id* primary key column from User table. Every user can be host or visitor many times and makes none or many requests.

@Entity
public class Request {
@Id
private Long req_id;

 ....

}


推荐答案

请求是针对主机和访问者的,所以您只需要从请求到用户有两个ManyToOne关联:

A request is for a host, and from a visitor, So you simply have 2 ManyToOne associations from Request to User:

@Entity
public class Request {
    @Id
    @Column(name = "req_id")
    private Long id;

    @ManyToOne
    @JoinColumn(name = "visitor_id")
    private User visitor;

    @ManyToOne
    @JoinColumn(name = "host_id")
    private User host;

    // ...
}

要使这些关联是双向的,那么你只需要在用户中对应的集合:

If you want to make these associations bidirectional, then you simply need corresponding collections in the user:

@Entity
private class User {

    /**
     * requests made to this user, in order for this user to be a host
     */
    @OneToMany(mappedBy = "host")
    private Set<Request> hostRequests = new HashSet<>();

    /**
     * requests made by this user, in order for this user to be a visitor
     */
    @OneToMany(mappedBy = "visitor")
    private Set<Request> visitorRequests = new HashSet<>();

    // ...
}

这篇关于使用来自相同表的两个外键进行休眠 - 注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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