I have three tables Student
, Department
, Student_Detail
Table Student
--------------
std_id (pk)
Table Student_Detail
--------------
std_id (pk)
Dept_ID (pk)
Table Department
--------------
Dept_ID (pk)
The mapping for Student.hbm.xml
<map name="studentDetails" table="STUDENT_DETAIL" lazy="false" >
<key column = "std_id">
<map-key-many-to-many column="Dept_ID" class="Department">
<element column="Remarks" type="string"/>
</map>
Now I want to write the detachedCriteria
for query
select * from student S
JOIN Student_Detail SD ON SD.std_id = S.std_Id
JOIN Department D ON D.dept_Id = SD.dept_Id
where AND D.name = 'x' and SD.remarks ='x'
Following DetachedCriteria
should work if your hibernate mapping is correct!
DetachedCriteria detachedCriteria = DetachedCriteria.forClass(
Student.class, "studentAlias");
detachedCriteria.createAlias("details", "detailsAlias")// details is collection of `StudentDetail` in `Student` class
.createAlias("detailsAlias.department", "departmentAlias")//department is `Department` type variable in `StudentDetail`
.add(Restrictions.eq("detailsAlias.remarks", "x"))
.add(Restrictions.eq("departmentAlias.name", "x"));
List<Student> list = detachedCriteria
.getExecutableCriteria(hibernateSession).setMaxResults(100)
.list();
for this i created class Student
, Department
, StudentDetail
class with following annotations.
@Entity
@Table(name = "student")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long std_id;
@OneToMany(mappedBy = "student", fetch = FetchType.LAZY)
@Fetch(FetchMode.SELECT)
private List<StudentDetail> details;
// getter/setters
}
@Entity
@Table(name = "department")
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long Dept_ID;
private String name;
private String remarks;
// getter/setters
}
@Entity
@Table(name = "student_detail")
public class StudentDetail {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToOne
@JoinColumn(name = "std_id")
@Fetch(FetchMode.SELECT)
private Student student;
@ManyToOne
@JoinColumn(name = "Dept_ID")
@Fetch(FetchMode.SELECT)
private Department department;
private String remarks;
// getter/setters
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.