我正在尝试使用JPA Criteria API编写以下SQL查询

SELECT * FROM roles WHERE roles.name IN (SELECT users.role FROM users where name="somename");


对我来说,这有点太多了(我刚刚开始学习Criteria API)。我得到这样的东西:

    CriteriaBuilder criteriaBuilder = manager.getCriteriaBuilder();
    CriteriaQuery<RoleEntity> criteriaQuery = criteriaBuilder.createQuery(RoleEntity.class);
    Root<RoleEntity> root = criteriaQuery.from(RoleEntity.class);

    Subquery<UserEntity> subquery = criteriaQuery.subquery(UserEntity.class);
    Root<UserEntity> subqueryRoot = subquery.from(UserEntity.class);
    subquery.where(criteriaBuilder.equal(subqueryRoot.get(UserEntity_.username), username));
    subquery.select(subqueryRoot);


而且我不知道如何将所有内容放在一起。

最好的祝福,
巴泰克

最佳答案

JPA学习者在这里。这是我尝试进行的设置:

// Get the criteria builder from the entity manager
CriteriaBuilder cb = manager.getCriteriaBuilder();

// Create a new criteria instance for the main query, the generic type indicates overall query results
CriteriaQuery<RoleEntity> c = cb.createQuery(RoleEntity.class);
// Root is the first from entity in the main query
Root<RoleEntity> role = criteriaQuery.from(RoleEntity.class);

// Now setup the subquery (type here is RETURN type of subquery, should match the users.role)
Subquery<RoleEntity> sq = cb.subquery(RoleEntity.class);
// Subquery selects from users
Root<UserEntity> userSQ = sq.from(UserEntity.class);
// Subquery selects users.role path, NOT the root, which is users
sq.select(userSQ.get(UserEntity_.role))
  .where(cb.equal(userSQ.get(UserEntity_.username), username)); // test for name="somename"

// Now set the select list on the criteria, and add the in condition for the non-correlated subquery
c.select(role)
  .where(cb.in(role).value(sq));  // can compare entities directly, this compares primary key identities automatically


希望有帮助!

关于java - JPA Criteria API中的简单CriteriaQuery对菜鸟来说实在太多了,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12569849/

10-16 05:12