Many-to-many on the same table with additional columns

后端 未结 3 517
终归单人心
终归单人心 2020-12-08 23:24

I have a class User. A user can be a friend with many other users. The relationship is mutual. If A is a friend of B then B is a friend of A. Also I want every relation to s

3条回答
  •  独厮守ぢ
    2020-12-08 23:51

    You have said

    many-to-many relationship on the same table

    It is not a good idea. It is a nightmare to maintain.

    Try this one instead

    @Entity
    public class Friend {
    
        @Id
        @GeneratedValue(strategy=GenerationType.AUTO)
        private Integer friendId;
    
        @Column
        private String name;
    
        @OneToMany(mappedBy="me")
        private List myFriends;
    
    }
    
    @Entity
    public class MyFriends {
    
        @EmbeddedId
        private MyFriendsId id;
    
        @Column
        private String additionalColumn;
    
        @ManyToOne
        @JoinColumn(name="ME_ID", insertable=false, updateable=false)
        private Friend me;
    
        @ManyToOne
        @JoinColumn(name="MY_FRIEND_ID", insertable=false, updateable=false)
        private Friend myFriend;
    
        @Embeddable
        public static class MyFriendsId implements Serializable {
    
            @Column(name="ME_ID", nullable=false, updateable=false)
            private Integer meId;
    
            @Column(name="MY_FRIEND_ID", nullable=false, updateable=false)
            private Integer myFriendId;
    
            public boolean equals(Object o) {
                if(o == null)
                    return false;
    
                if(!(o instanceof MyFriendsId))
                    return false;
    
                MyFriendsId other = (MyFriendsId) o;
                if(!(other.getMeId().equals(getMeId()))
                    return false;
    
                if(!(other.getMyFriendId().equals(getMyFriendId()))
                    return false;
    
                return true;
            }
    
            public int hashcode() {
                // hashcode impl
            }
    
        }
    
    
    }
    

    regards,

提交回复
热议问题