2013-04-07 100 views
0

我有兩個目標用戶和聯繫人,以多對多的關係,我使用一箇中間表此關係USER_CONTACTHibernate的多對許多數據檢索

保存數據,這個協會是好的,但檢索是一個問題。

我需要檢索基於用戶的數據,但我得到的是所有用戶的聯繫人。

如果你能讓我知道我在做什麼錯,那將是一件好事。

public class User { 
private Integer userID; 
private String userLoginEmail; 
private String password; 
private Set<Contact> contactSet = new HashSet<Contact>(); 
. 
. 
} 

public class Contact implements Serializable { 
private Integer contactID; 
private String givenName; 
private String familyName; 
private Set<User> userSet = new HashSet<User>(); 
. 
. 
} 

User.hbm.xml:

<class name="User" table="USERACCOUNT"> 
    <id column="USER_ID" length="500" name="userID"> 
     <generator class="increment" /> 
    </id> 
    <property column="USER_LOGIN_EMAIL" generated="never" lazy="false" length="100" name="userLoginEmail" /> 
    <property column="USER_FIRSTNAME" generated="never" lazy="false" length="100" name="userFirstName" /> 
    <property column="USER_LASTNAME" generated="never" lazy="false" length="100" name="userLastName" /> 
    <set name="contactSet" table="USER_CONTACT" inverse="false" lazy="false" fetch="select" cascade="all"> 
     <key column="USER_ID"/> 
     <many-to-many column="CONTACT_ID" class="com.smallworks.model.Contact"/> 
    </set> 
</class> 

Contact.hbm.xml

<class name="Contact" table="CONTACT"> 
    <id column="CONTACT_ID" length="500" name="contactID"> 
    <generator class="increment"/> 
    </id> 
    <property column="GIVEN_NAME" generated="never" lazy="false" length="100" name="givenName"/> 
    <property column="FAMILY_NAME" generated="never" lazy="false" length="100" name="familyName"/> 

    <!-- many to many mapping with the User via User_Contact table --> 
    <set inverse="true" lazy="false" name="userSet" sort="unsorted" table="USER_CONTACT"> 
    <key column="USER_ID"/> 
    <many-to-many class="com.smallworks.model.Contact" column="CONTACT_ID" unique="false"/> 
    </set> 
</class> 

,這是我正在試圖檢索數據,我認爲這是不正確。

List contactList = session.createQuery("from Contact").list(); 

如果我能知道如何去獲取基於用戶的聯繫人將是一件好事。

回答

3
// First, retrieve the user you want. 
User user = (User) session.get(User.class, user_id_you_want); 
// Second, get the contacts of that given user and add them to a list (optional) 
List contacts = new ArrayList(); 
contacts.addAll(user.getContactSet()); 
return contacts; 
+0

Thanx,它的工作,我應該意識到,並且因爲它的延遲加載正確的集合已經在用戶對象。 – Harbir 2013-04-10 02:01:49

+0

嗨@Yori Kusanagi,我試圖做一個查詢以上,看看http://stackoverflow.com/questions/17653399/hibernate-many-to-many-data-retrival-via-query?noredirect = 1#comment25714062_17653399 您可以請看看,看看您是否可以幫助查詢。 – Harbir 2013-07-16 00:04:12