2013-04-09 64 views
0

我有兩個玩JPA對象User.java & UserRole.JavaJPDA查詢和播放 - 用戶和角色(JOIN)

public User(String email, String password, String firstName, String lastName, Status status, List<UserRole> roles){ 
     this.email = email; 
     this.password = password; 
     this.firstName = firstName; 
     this.lastName = lastName; 
     this.status = status; 
     this.roles = roles; 
    } 

UserRole的

public UserRole(User user,RoleType roleType, Status status) { 
     this.user = user; 
     this.roleType = roleType; 
     this.status = status; 
    } 

是的UserRole通過

映射到用戶
@OneToMany(mappedBy="user",fetch=FetchType.EAGER) 
public List<UserRole> roles; 

我希望寫一個播放JPQL查詢,將返回所有用戶與指定的RO這是否可能,如果是這樣,如何?

回答

0

因爲你已經設計了你的模型,有兩個表User.java & UserRole.java),實現你的目標並不複雜。

如果您User.java模型擴展play.db.jpa.Model類,解決方案可能是象下面這樣:

// by using nested query to find all user that has admin role 
List<User> userList = User.find(
    "id IN (SELECT user FROM models.UserRole WHERE roleType = ?)", 
    RoleType.ADMIN 
).fetch(); 

上述表達式是相同的SQL查詢:

SELECT * FROM "user" WHERE id IN (
    SELECT user_id FROM user_role WHERE role_type = 'ADMIN' 
);