Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
948 views
in Technique[技术] by (71.8m points)

java - 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;

 ....

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

    // ...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...