-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 
Author Message
 Post subject: Criteria and subqueries: how to make a not-in statement?
PostPosted: Tue Oct 26, 2010 3:36 am 
Newbie

Joined: Tue Oct 26, 2010 3:18 am
Posts: 2
I'm sure this has been posted before, but I couldn't find an answer that really seemed to cover my problem.

I have two tables, with a one-to-one relation. One table has a few thousand records, the other one just a few. Simplified, it looks something like this:

Code:
Table Person (lots of records)
id - Long
name - String
{etc}
Table Subscription (handful of records)
id - Long
person_id - Long
{etc}


Now, I would like to use Criteria to get a set of persons, that does not have a record on the subscription table. Normally using SQL (postGres is this case), I'd write something like this:
Code:
select {Person columns} from person where id not in (select per.id from subscription sub inner join person per on per.id = sub.person_id)


Now getting that sql translated to criteria doesn't really seem to work for me (or rather, I can't get it to work properly). I've tried several things among the lines of:
Code:
DetachedCriteria criteria = DetachedCriteria.forClass(Person.class);
DetachedCriteria subCriteria = DetachedCriteria.forClass(Subscription.class);
subCriteria.createAlias("person", "person");
criteria.add(Subqueries.notIn("", subCriteria));


What am I doing wrong here?

Thanks in advance


Top
 Profile  
 
 Post subject: Re: Criteria and subqueries: how to make a not-in statement?
PostPosted: Tue Oct 26, 2010 8:51 am 
Newbie

Joined: Tue Oct 26, 2010 3:18 am
Posts: 2
Ok, I found it out. The trick that worked for me was to specifically create an alias to the outter criteria, and then use PropertyNotIn:
Code:
String critAlias = "prsn";
DetachedCriteria criteria = DetachedCriteria.forClass(Person.class, critAlias)
DetachedCriteria subCriteria = DetachedCriteria.forClass(Subscription.class);
subCriteria.setProjection(Projections.property("Person"));
criteria.add(Subqueries.propertyNotIn(critAlias+".id", subCriteria));


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.