gpt4 book ai didi

java - 如何编写java hibernate多对多关系检索查询

转载 作者:行者123 更新时间:2023-11-30 04:44:47 24 4
gpt4 key购买 nike

我有两个表,如下所示。我想编写一个查询来获取特定组的所有联系人。(根据组 ID)。请帮我。提前致谢。

1.这个联系人表,里面有很多与联系人组有多对多关系的表。

@Entity
@Table(name="contacts")
public class Contacts implements Serializable {
private Long id;
private String userId;
private String emailId;
private Set<ContactGroups> contactGroups;
private String firstName;
private String lastName;

@Id
@Column(name="id")
@GeneratedValue(strategy=GenerationType.AUTO)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}

@Column(name="user_id")
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}

@Column(name="email_id")
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}

@ManyToMany(targetEntity = ContactGroups.class, cascade = {CascadeType.ALL},fetch=FetchType.EAGER)
@JoinTable(name="contact_group",
joinColumns=@JoinColumn(name="c_id", referencedColumnName="id"),
inverseJoinColumns=@JoinColumn(name="g_id", referencedColumnName="id")
)
public Set<ContactGroups> getContactGroups() {
return contactGroups;
}
public void setContactGroups(Set<ContactGroups> contactGroups) {
this.contactGroups = contactGroups;
}

@Column(name="first_name")
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
@Column(name="last_name")
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}


}





@Entity
@Table(name="contact_groups")
public class ContactGroups implements Serializable{
private Long id;
private String groupName;
private String userName;

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}

@Column(name="user_name")
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}

@Column(name="group_name")
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}


}

最佳答案

select c from Contacts c 
inner join c.contactGroups group
where group.id = :groupId

但是如果

一切都会变得更简单
  • 您为实体命名为 ContactGroupContact(没有最后的 s)
  • 您将关联映射为双向关联。它将允许通过 ID 获取 ContactGroup,并且只需调用 getContacts() 即可获取其联系人。

关于java - 如何编写java hibernate多对多关系检索查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11290096/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com