JPQL和Join Table

时间:2012-11-21 03:10:28

标签: java jpa jpql

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

编辑:Woops我忘了将用户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;
}

1 个答案:

答案 0 :(得分:9)

使用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类的实例。如果您只有用户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);

最好使用SetSortedSet(如果用户可以多次出现在同一组中,则可能是List而不是{{1} }。