我有三个表Student
,Department
,Student_Detail
Table Student
--------------
std_id (pk)
Table Student_Detail
--------------
std_id (pk)
Dept_ID (pk)
Table Department
--------------
Dept_ID (pk)
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>
现在我想为查询编写detachedCriteria
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'
答案 0 :(得分:0)
如果你的hibernate映射是正确的,DetachedCriteria
之后应该有效!
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();
为此我创建了一个包含以下注释的课程Student
,Department
,StudentDetail
课程。
@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
}