Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate Criteria query Collections contains certain elements

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

like image 994
maracili Avatar asked Jan 05 '15 13:01

maracili


1 Answers

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)));
}
like image 110
WeMakeSoftware Avatar answered Oct 26 '22 19:10

WeMakeSoftware