Hibernate with two foreign keys from same table- annotation

后端 未结 1 1771
广开言路
广开言路 2021-01-02 20:23

I\'m trying to design a hospitality app. I have two tables as User and Request. Users could be Host or Visitor and can se

相关标签:
1条回答
  • 2021-01-02 20:33

    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<>();
    
        // ...
    }
    
    0 讨论(0)
提交回复
热议问题