2012-12-13 164 views
1

我使用休眠并试图表示用户与朋友的关系。我的第一个想法是用一组朋友对象创建一个用户对象。hibernate创建用户对朋友关系

我愿与所有用户和像信息用户表:

用户表:第一个名字,姓氏等

然后一个User_Friend表来管理的关系。喜欢的东西:

* User_Friend表:ID,用户id,friendId(用户ID)*

用户将有许多friendIds。

我已经创建了一个用户对象的表和映射:

<id name="id" type="int"> 
     <column name="userId" /> 
      <generator class="native" /> 
     </id> 
     <set name="friends" table="User_Friend???" 
       inverse="true" lazy="true" fetch="select"> 
      <key> 
       <column name="userId" not-null="true" /> 
      </key> 
      <many-to-many entity-name="Friend"> 
       <column name="friendId" not-null="true" /> 
      </many-to-many> 
     </set> 
     <property name="firstName" type="string"></property> 
     <property name="lastName" type="string"></property> 
     <property name="email" type="string"></property> 

什么会为我的朋友的对象映射的样子,如果我想保持朋友的信息(如名字,姓氏等。)在用户表中的关系和像User_Friend这样的表中的关系?

作为本质上的用户,我应该如何处理朋友?如果是的话,我会将上面的User_Friend表更改为User表?

编辑: 我发现这个link to hibernate ref这也解释了双向一对多/多对一与连接表。
这将允许我创建一个用户到朋友的关系,而无需复制用户表(朋友)?

谢谢!

回答

1

你在找什么是“许多一对多在Hibernate中自我引用”

在下面的例子中,员工可以有很多同事:

Self reference many to many

@Entity 
@Table(name="EMPLOYEE") 
public class Employee { 

    //id, firstname, lastname 

    @ManyToMany(cascade={CascadeType.ALL}) 
    @JoinTable(name="EMPLOYEE_COLLEAGUE", 
     joinColumns={@JoinColumn(name="EMPLOYEE_ID")}, 
     inverseJoinColumns={@JoinColumn(name="COLLEAGUE_ID")}) 
    private Set<Employee> colleagues = new HashSet<Employee>(); 

    @ManyToMany(mappedBy="colleagues") 
    private Set<Employee> teammates = new HashSet<Employee>();  

    // Getter and Setter methods 
} 

请参见教程: Many to many hibernate self referencing

-1

尝试两个表:

Users -- with your user information 
user_friends -- with two user_ids representing a friendship. 

你的业务逻辑可以指示的关系是双向或单向。