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

瘦欲@ 提交于 2019-11-28 07:02:09

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> 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,

I'm not sure this will fit your case, but give it a try.

@Entity
public class Friend {

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

    @Column
    private String name;

    @ManyToMany(mappedBy="owner")
    private List<Friendship> friendships;
}

@Entity
public class Friendship {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int friendshipId;

    @OneToOne
    private Friend owner;

    @OneToOne
    private Friend target;

   // other info
}

I had the same problem. You can try something like this:

<class name="Friend" entity-name="RelatedFriend" table="FRIENDS">
    <id name="id" type="long">
        <generator class="native" />
    </id>

    <!-- *** -->

    <set name="relatedFriends" table="RELATED_FRIENDS">
        <key column="FRIEND_ID" />
        <many-to-many column="RELATED_FRIEND_ID" class="Friend" entity-name="RelatedFriend"/>
    </set>
</class>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!