Hibernation request criteria Collections contain specific items

I have some problems with Criteria

. I have a class Job

that contains a set Skills

.

The problem arises when I want to filter jobs that contain 2 skills, for example, all jobs that contain skills with IDs 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 he gives me tasks that contain skill 1 or 3, not just 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 tried this but sql and (skill1_.ID=? and skill1_.ID=?)

with no results

+3


source to share


3 answers


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.

0


source


Try the following:



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)));
}

      

0


source


the result you get is expected. you are using Restrictions.in

, you can useCriterion

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);
}

      

0


source







All Articles