2014-06-05 44 views
0

我正在使用JPA 2.0,Hibernate 4.1.0.Final和MySQL 5.5。我有兩個班,Group和GroupMember。 GroupMember類鏈接到Group類,像這樣...如何選擇JPA中的實體的一部分(不是JPQL)?

public class GroupMember 
{ 

    @Id 
    @NotNull 
    @GeneratedValue(generator = "uuid-strategy") 
    @Column(name = "ID") 
    private String id; 

    @ManyToOne 
    @JoinColumn(name = "USER_ID", nullable = false, updatable = true) 
    private User user; 

    @ManyToOne 
    @JoinColumn(name = "GROUP_ID", nullable = false, updatable = true) 
    private Group group; 

如何編寫JPA查詢以便獲取用戶所在的所有組?我無法選擇「組」唯一的,作爲標準條款是圍繞GroupMember對象...

final CriteriaBuilder builder = m_entityManager.getCriteriaBuilder(); 
    CriteriaQuery<GroupMember> criteria = builder.createQuery(GroupMember.class); 
    final Root<GroupMember> groupMemberRoot = criteria.from(GroupMember.class); 
    criteria.multiselect(groupMemberRoot.get(GroupMember_.group)).where(builder.equal(groupMemberRoot.get(GroupMember_.user), user)); 
    TypedQuery<Group> results = m_entityManager.createQuery(criteria); // doesn’t compile 

最後一行無法編譯,希望有人知道正確的語法是什麼。

+0

不能用一些編譯器錯誤消息編譯... –

回答

0

您的代碼無法編譯,因爲您必須創建一個CriteriaQuery<Group>。試試這個:

final CriteriaBuilder builder = m_entityManager.getCriteriaBuilder(); 
CriteriaQuery<Group> criteria = builder.createQuery(Group.class); 
final Root<GroupMember> groupMemberRoot = criteria.from(GroupMember.class); 
criteria.select(groupMemberRoot.get(GroupMember_.group)); 
criteria.where(builder.equal(groupMemberRoot.get(GroupMember_.user), user)); 
TypedQuery<Group> results = m_entityManager.createQuery(criteria);