简体   繁体   English

使用来自相同表注释的两个外键来休眠

[英]Hibernate with two foreign keys from same table- annotation

I'm trying to design a hospitality app. 我正在尝试设计一个酒店应用程序。 I have two tables as User and Request . 我有两个表作为UserRequest Users could be Host or Visitor and can send host request to each other. 用户可以是HostVisitor ,可以向对方发送主持人请求。 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). 这种差异在申请表中只是重要的,它需要保持visitor_idhost_id为外键(用映射user_id从用户表的主键列,因为主机和访客也用户)。

My question is how can I define this relation in hibernate with Annotation ? 我的问题是如何在Hibernate中使用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. 我的意思是,Request表中应该有两个外键,它们被映射到User表中的* user_id *主键列。 Every user can be host or visitor many times and makes none or many requests. 每个用户可以多次成为主持人或访问者,并且不会发出任何请求。

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

 ....

}

A request is for a host, and from a visitor, So you simply have 2 ManyToOne associations from Request to User: 请求是针对主机的,也是来自访问者的,因此您只需要从请求到用户的2个ManyToOne关联:

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

    // ...
}

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

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