繁体   English   中英

休眠多对多数据检索

[英]Hibernate many-to-many data retrieval

我有两个对象User和Contact,具有多对多关系,并且我为此关系使用一个中间表USER_CONTACT

将数据保存在此关联中很好,但是检索是一个问题。

我需要根据用户检索数据,但是我得到的是所有用户的所有联系人。

如果您能让我知道我在做什么错,那将是很好的。

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();

如果我能知道如何根据用户获取联系人,那将是很好的。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM