Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
662 views
in Technique[技术] by (71.8m points)

nhibernate - Hibernate Criteria for "in subselect"

I'm trying to do something like this, but using Criteria instead of HQL:

select user from User where user in (
    select user from UserDomain where domain.id = "XXX"
)

User being an entity having a one-to-many relationship to the join table UserDomain. The point here is simply to find Users that are linked to a Domain having id = "XXX".

This seems like it should be very simple... but I'm having no luck so far turning up any useful docs.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The subquery is very useful in cases, that you need to search the User, having one-to-many UserDomains. In that case, the WHERE UserId IN (subquery) brings big advanatage: we are still working with a flat User table/entity... so we can do the proper paging.

Here is the documentation 15.8. Detached queries and subqueries

The draft could be: subquery:

DetachedCriteria userSubquery = DetachedCriteria.forClass(UserDomain.class, "ud")
    // Filter the Subquery
    .add(Restrictions.eq(UserDomain.DOMAIN, domain))
    // SELECT The User Id  
    .setProjection( Projections.property("ud.userId") );

And the main query:

Criteria query = session.createCriteria(User.class, "u")
    .add( Subqueries.propertyIn("u.id", userSubquery) );

Now we have a query, which could be used for paging


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...