【问题标题】:Hibernate many-to-many data retrievalHibernate 多对多数据检索
【发布时间】:2013-03-29 22:20:35
【问题描述】:

我有两个对象 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>();
.
.
}

用户.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>

联系人.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();

如果我能知道如何根据用户获取联系人,那就太好了。

【问题讨论】:

    标签: java hibernate jakarta-ee orm hibernate-mapping


    【解决方案1】:
    // 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;
    

    【讨论】:

    • 谢谢,它起作用了,我应该意识到这一点,并且由于它的延迟加载正确的集合已经在 User 对象中。
    • 嗨@Yori Kusanagi,我正在尝试通过查询来完成上述操作,看看stackoverflow.com/questions/17653399/…你能看看你是否可以帮助查询。
    猜你喜欢
    • 2013-07-13
    • 1970-01-01
    • 2017-11-18
    • 2017-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-17
    • 2012-12-26
    相关资源
    最近更新 更多