一尘不染

JPQL和联接表

java

我对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]

编辑:糟糕,我忘记了按用户ID将搜索添加到查询中。我想获取用户所属的所有组。

但是我只是语法不正确。任何帮助将不胜感激。

相关代码段:

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

@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;
}

阅读 238

收藏
2020-12-03

共1个答案

一尘不染

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

这里em是您的EntityManager,user是要为其加载组列表的User类的实例。如果只有用户标识,请更改:

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

最好使用SetSortedSetList如果用户可以在同一组中不止一次,则可以使用),而不要使用Collection

2020-12-03