代码之家  ›  专栏  ›  技术社区  ›  Petar Minchev

同一个表上的多对多以及其他列

  •  10
  • Petar Minchev  · 技术社区  · 16 年前

    3 回复  |  直到 16 年前
        1
  •  7
  •   Arthur Ronald    15 年前

    你说过

    在同一张桌子上

    @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
            }
    
        }
    
    
    }
    

    当做

        2
  •  2
  •   Bozho    16 年前

    @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
    }
    
        3
  •  1
  •   Bo.    16 年前

    我也有同样的问题。您可以尝试以下方法:

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