2012-11-21 72 views
5

我的SQL和JPQL的理解都不是偉大的,我一直在試圖創建下面的SQL語句的JPQL查詢: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; 
} 
+0

你想做什麼? –

回答

8

使用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是您的電子ntityManager和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如果用戶可以在同一組不止一次),而不是Collection