Guest User

Untitled

a guest
Jan 21st, 2019
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.62 KB | None | 0 0
  1. SELECT * FROM roles WHERE roles.name IN (SELECT users.role FROM users where name="somename");
  2.  
  3. CriteriaBuilder criteriaBuilder = manager.getCriteriaBuilder();
  4. CriteriaQuery<RoleEntity> criteriaQuery = criteriaBuilder.createQuery(RoleEntity.class);
  5. Root<RoleEntity> root = criteriaQuery.from(RoleEntity.class);
  6.  
  7. Subquery<UserEntity> subquery = criteriaQuery.subquery(UserEntity.class);
  8. Root<UserEntity> subqueryRoot = subquery.from(UserEntity.class);
  9. subquery.where(criteriaBuilder.equal(subqueryRoot.get(UserEntity_.username), username));
  10. subquery.select(subqueryRoot);
  11.  
  12. // Get the criteria builder from the entity manager
  13. CriteriaBuilder cb = manager.getCriteriaBuilder();
  14.  
  15. // Create a new criteria instance for the main query, the generic type indicates overall query results
  16. CriteriaQuery<RoleEntity> c = cb.createQuery(RoleEntity.class);
  17. // Root is the first from entity in the main query
  18. Root<RoleEntity> role = criteriaQuery.from(RoleEntity.class);
  19.  
  20. // Now setup the subquery (type here is RETURN type of subquery, should match the users.role)
  21. Subquery<RoleEntity> sq = cb.subquery(RoleEntity.class);
  22. // Subquery selects from users
  23. Root<UserEntity> userSQ = sq.from(UserEntity.class);
  24. // Subquery selects users.role path, NOT the root, which is users
  25. sq.select(userSQ.get(UserEntity_.role))
  26. .where(cb.equal(userSQ.get(UserEntity_.username), username)); // test for name="somename"
  27.  
  28. // Now set the select list on the criteria, and add the in condition for the non-correlated subquery
  29. c.select(role)
  30. .where(cb.in(role).value(sq)); // can compare entities directly, this compares primary key identities automatically
Add Comment
Please, Sign In to add comment