Reputation: 465
A Student class has OneToOne association with an Object of type Resume and Resume class has a OneToMany association with a collection of type Master and master has a property degreeName. What i want to achieve is:
select all the students where student.resume.masters.degreeName in (?,?,?,.....)
It should search in all the collection(Master) objects.
Below code has no compilation error but It is not giving expected result please correct me.
Student Entity:
@Entity
public class Student {
@OneToOne(fetch = FetchType.LAZY, mappedBy = "student", cascade = CascadeType.ALL)
private Resume resume;
}
Resume Entity:
@Entity
public class Resume {
@OneToMany(mappedBy="resume",cascade=CascadeType.ALL)
private List<Master> masters=new ArrayList<>();
@OneToOne(fetch=FetchType.LAZY)
@PrimaryKeyJoinColumn
private Student student;
}
Master Entity:
@Entity
public class Master {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="resume_id")
private Resume resume;
private String degreeName;
}
Dao:
Criteria studentCriteria = session.createCriteria(Student.class);
Criteria resumeCriteria = studentCriteria.createCriteria("resume");
Criteria mastersCriteria = resumeCriteria.createCriteria("masters");
List<String> degreeslist = new ArrayList<>(Arrays.asList(degrees));
//degreeList is collection of values on which the student will be searched
if (degreeslist.size() == 1) {
mastersCriteria.add(Restrictions.eq("degreeName",
degreeslist.get(0)));
} else {
mastersCriteria.add(Restrictions.in("degreeName", degreeslist));
}
Upvotes: 4
Views: 571
Reputation: 26094
Criteria mastersCriteria = getSession().createCriteria(Student.class, "student");
mastersCriteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
mastersCriteria.createAlias("student.resume", "resume");
mastersCriteria.createAlias("resume.masters","masters");
if (degreeslist.size() == 1) {
mastersCriteria.add(Restrictions.eq("masters.degreeName", degreeslist.get(0)));
} else {
mastersCriteria.add(Restrictions.in("masters.degreeName", degreeslist));
}
List<Student> students = mastersCriteria.list();
Upvotes: 4