2012-12-13 75 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. 

你的業務邏輯可以指示的關係是雙向或單向。