【问题标题】:Simple CriteriaQuery in JPA Criteria API that is too much for a noobJPA Criteria API 中的简单 CriteriaQuery 对于菜鸟来说太多了
【发布时间】:2012-09-24 17:22:24
【问题描述】:

我正在尝试使用 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,我以前使用过 Hibernate 的 Criteria,但我一直远离 JPA Criteria。它的复杂性没有给我带来任何附加值。
  • 好吧,我同意,这太复杂了。

标签: java hibernate jpa criteria-api


【解决方案1】:

这里是 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

希望对您有所帮助!

【讨论】:

  • 你是怎么用userSQ.select(userSQ.get(UserEntity_.role)) .where(cb.equal(userSQ.get(UserEntity_.username), username));照这个的:linkRoot界面没有select这种方法。
猜你喜欢
  • 2020-08-08
  • 1970-01-01
  • 1970-01-01
  • 2018-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多