Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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).

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;

 ....

}
like image 512
bisorniyesordum Avatar asked Apr 09 '14 06:04

bisorniyesordum


1 Answers

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

    // ...
}
like image 149
JB Nizet Avatar answered Sep 19 '22 12:09

JB Nizet