8

I have some problems with Criteria. I have a Job class that contains a set of Skills.

The problem comes when I want to filter jobs that contain 2 skills, for example, all jobs that contains skill with id 1 and 3.

Now I have this:

for (Skill skill : job.getSkills()) {
    ids.add(skill.getId());
}

criteria.createAlias("skills", "skill");
criteria.add(Restrictions.in("skill.id", ids));

but it gives me jobs that contain skill 1 or 3, not only those with both skills. How can I do this?

UPDATE:

criteria.createAlias("Job.skills", "skill");    
Conjunction and = Restrictions.conjunction();   

for (Skill skill : job.getSkills()) {
    and.add(Restrictions.eq("skill.id", skill.getId()));
}
criteria.add(and);

I've tried this but the sql is and (skill1_.ID=? and skill1_.ID=?) with no results

Micho
  • 3,929
  • 13
  • 37
  • 40
maracili
  • 181
  • 1
  • 3
  • 15

3 Answers3

1

Try this one:

criteria.createAlias("skills", "skill");

for(Skill skill:job.getSkills()){
    List<Long> wrappedParameter = new ArrayList<Long>();
    wrappedParameter.add(skill.getId());
    criteria.add(Restrictions.in("skill.id", wrappedParameter)));
}
WeMakeSoftware
  • 9,039
  • 5
  • 34
  • 52
0

the result you are getting is expected. you are using Restrictions.in you can use Criterion

List<Criterion> restrictionList;
for(Skill skill :job.getSkills()){
    //ids.add(skill.getId());
    Criterion ctn=Restrictions.eq("skill.id", skill.getId());
    restrictionList.add(ctn);
}

criteria.createAlias("skills", "skill");
for (Criterion crit : restrictionList){
   criteria.add(crit);
}
void
  • 7,760
  • 3
  • 25
  • 43
  • Thanks for response but this returns me an empty list. query generated for skills is : "and skill1_.ID=? and skill1_.ID=?" – maracili Jan 05 '15 at 14:27
0
for(Skill skill:job.getSkills()){
                    DetachedCriteria subquery = DetachedCriteria.forClass(Skill.class,"skill");
                    subquery.add(Restrictions.eq("id",skill.getId()));
                    subquery.setProjection(Projections.property("id"));
                    subquery.createAlias("jobs", "job");
                    subquery.add(Restrictions.eqProperty("job.id", "Job.id"));
                    criteria.add(Subqueries.exists(subquery));  
                }

I managed to solve it.now it works.

maracili
  • 181
  • 1
  • 3
  • 15
  • The Skill class has a reference back to the Job class (bidirectional)? Can this solution be adapted to a unidirectional configuration? I.e., a Job has a collection of Skill, but Skill knows nothing about Job? What is the value of "Job.id" ? – chrisinmtown Aug 22 '18 at 17:27