2012-09-24 111 views
1

我想寫使用JPA標準API簡單CriteriaQuery中是太多了小白

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

以下SQL查詢,這是一個有點多,我(我剛開始性學習的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); 

而我不知道如何把它放在一起。

最好的問候, 鮑爾泰克

+2

只是一個觀點:我喜歡JPA,我之前使用過Hibernate的'Criteria',但我已經遠離JPA'Criteria'。它的複雜性給我帶來了額外的價值。 – madth3

+0

嗯,我同意,這是複雜的方式。 – BartoszCichecki

回答

4

研究員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 

希望有幫助!

+0

你是如何使用'userSQ.select(userSQ.get(UserEntity_.role)) .where(cb.equal(userSQ.get(UserEntity_.username),username));'根據這個:[link]( http://docs.oracle.com/javaee/6/api/javax/persistence/criteria/Root.html)在Root界面中沒有選擇這種方法。 – BartoszCichecki

+0

哎呀!這應該是平方米! –