具有附加列的同一个表上的多对多

Pet*_*hev 11 mapping orm many-to-many hibernate

我有一个类用户.用户可以是许多其他用户的朋友.这种关系是相互的.如果A是B的朋友,则B是A的朋友.此外,我希望每个关系都存储其他数据 - 例如,两个用户成为朋友的日期.所以这是一个多对多的关系,在同一个表上有额外的列.我知道应该创建一个中产阶级友谊(包含两个用户ID和日期列).但我很想用Hibernate映射它.阻止我的是映射到同一个表.如果两个不同的表之间存在多对多关系,我可以解决它.

Art*_*ald 7

你说过

同一桌子上的多对多关系

这不是一个好主意.维持这是一场噩梦.

试试这个

@Entity
public class Friend {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer friendId;

    @Column
    private String name;

    @OneToMany(mappedBy="me")
    private List<MyFriends> 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
        }

    }


}
Run Code Online (Sandbox Code Playgroud)

问候,