Querydsl:innerJoin和JPASubQuery

时间:2015-08-06 14:53:52

标签: java-ee querydsl

如何使用Querydsl实现此SQL查询?

SELECT UserProfile.* FROM UserAccount_has_Workgroup 
INNER JOIN UserAccount ON UserAccount_has_Workgroup.userAccountID=UserAccount.userAccountID 
INNER JOIN UserProfile ON UserAccount.userAccountID = UserProfile.userAccountID
WHERE UserAccount_has_Workgroup.UserAccountID NOT IN
    (SELECT UserAccountID FROM UserAccount_has_Workgroup WHERE workgroupID = 2)
AND UserAccount.roleId <> 2;

我尝试过这个,但它返回一个空结果:

JPAQuery query = new JPAQuery(entityManager); 

query = query.from(userAccountHasWorkgroup)
     .innerJoin(userAccountHasWorkgroup.userAccountByUserAccountId, userAccount)
     .innerJoin(userAccountHasWorkgroup.userAccountByUserAccountId.userProfile, qUserProfile)
    .where(userAccountHasWorkgroup.userAccountByUserAccountId
       .notIn(new JPASubQuery().from(userAccountHasWorkgroup)
                .where(userAccountHasWorkgroup.workgroup.id.eq(workgroupId))
                .list(userAccountHasWorkgroup.userAccountByUserAccountId))
            )
   .where(userAccountHasWorkgroup.userAccountByUserAccountId.role.name.ne(role.getRoleString()))
        ;

  List<UserProfile>  results = query.list(userProfile);

2 个答案:

答案 0 :(得分:0)

在您的示例中,看起来WHERE表达式完全不同:

AND UserAccount.roleId <> 2;

VS

 where(userAccountHasWorkgroup.userAccountByUserAccountId.role.name.ne(role.getRoleString()))

另外我认为你不能连续使用两个WHERE表达式,但应该

.where(expr1.and(expr2))

就像在本机SQL

中一样

答案 1 :(得分:0)

尝试此查询,显然结果是我期望的结果::

JPAQuery query = new JPAQuery(entityManager); 

query = query.from(userAccount)     
        .innerJoin(userAccount.userProfile, userProfile)
        .where(userAccount.notIn(new JPASubQuery()
            .from(userAccountHasWorkgroup).where(userAccountHasWorkgroup.workgroup.id.eq(workgroupId))
            .list(userAccountHasWorkgroup.userAccountByUserAccountId)))
        .where(userAccount.role.name.ne(role.getRoleString()));

UserAccount表格传递(UserAccountN<-->N的{​​{1}}关系)