Java 休眠多对多数据检索
我有两个对象User和Contact,它们具有多对多关系,并且我正在为这个关系User\u Contact使用一个中间表 在这个关联中保存数据是可以的,但是检索是一个问题 我需要根据用户检索数据,但我得到的是所有用户的所有联系人 如果你能让我知道我做错了什么就好了Java 休眠多对多数据检索,java,hibernate,jakarta-ee,orm,hibernate-mapping,Java,Hibernate,Jakarta Ee,Orm,Hibernate Mapping,我有两个对象User和Contact,它们具有多对多关系,并且我正在为这个关系User\u Contact使用一个中间表 在这个关联中保存数据是可以的,但是检索是一个问题 我需要根据用户检索数据,但我得到的是所有用户的所有联系人 如果你能让我知道我做错了什么就好了 public class User { private Integer userID; private String userLoginEmail; private String password; private Set<
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>();
.
.
}
如果我能知道如何根据用户获取联系人,那就太好了。Thanx,它成功了,我应该意识到,由于它懒散地加载正确的集合已经在用户对象中了。Hi@Yori Kusanagi,我正试图通过一个查询来完成上述操作,看一看,你能看一看,看看你是否能帮上忙吗?Thanx,它成功了,我应该意识到,因为它懒散地加载正确的集合已经在用户对象中了。嗨@Yori Kusanagi,我正试图用一个查询来完成上面的工作,请看一看,看看你是否能帮上忙。
// 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;
<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;