简体   繁体   English

JPQL和Join Table

[英]JPQL and Join Table

My understanding of SQL and JPQL are not that great and I have been trying to create a JPQL query of the following sql statement: 我对SQL和JPQL的理解不是很好,我一直在尝试创建以下sql语句的JPQL查询:

select group.* from user, user_group, group 
where user_group.user_id = user.id 
and user_group.group_id = group.id 
and user.id = [userID to search]

edit: Woops I forgot to add the search by user id part to the query. 编辑:Woops我忘了将用户id部分的搜索添加到查询中。 I would like to get all groups that a user belongs in. 我想获得用户所属的所有群组。

But I just cannot get the syntax correct. 但我只是无法使语法正确。 Any help would be greatly appreciated. 任何帮助将不胜感激。

Relevant code snippets: 相关代码段:

Group.java Group.java

@Table(name = "group")
@Entity
public class Group implements Serializable {

@Id
@GeneratedValue
@Column(name = "id")
private Integer id;

@JoinTable(name = "user_group", joinColumns = {
    @JoinColumn(name = "group_id", referencedColumnName = "id")}, inverseJoinColumns = {
    @JoinColumn(name = "user_id", referencedColumnName = "id")})
@ManyToMany
private Collection<User> userCollection;

}

User.java User.java

@Table(name = "user")
@Entity
public class User implements Serializable {

@Id
@NotNull
@GeneratedValue
@Column(name = "id")
private Integer id;

@Column(name = "email", unique=true, nullable=false)
private String email;

@ManyToMany(mappedBy = "userCollection")
private Collection<Group> GroupCollection;
}

Using JPQL it would be: 使用JPQL它将是:

TypedQuery<Group> query = em.createQuery(
    "SELECT DISTINCT g FROM User u LEFT JOIN u.groupCollection g " +
    "WHERE u = :user", Group.class);
query.setParameter("user", user);
List<Group> = query.getResultsList();

where em is your EntityManager and user is the instance of the User class for which to load group list. 其中em是您的EntityManager, user是要加载组列表的User类的实例。 If you only have the user id, change with: 如果您只有用户ID,请更改为:

TypedQuery<Group> query = em.createQuery(
    "SELECT DISTINCT g FROM User u LEFT JOIN u.groupCollection g " +
    "WHERE u.id = :user", Group.class);
query.setParameter("user", userId);

It would be better to use a Set or SortedSet (or maybe a List if the user can be in the same group more than once) instead of a Collection . 最好使用SetSortedSet (如果用户可以多次在同一组中,则可以使用List ),而不是Collection

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

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