0

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'
Aniket Kulkarni
  • 12,825
  • 9
  • 67
  • 90
Krishna
  • 321
  • 1
  • 6
  • 15
  • The mapping with a `` seems to be overcomplicated to me. If you have a chance to change a pairing table - to have its own surrogated key, please, try to read this: http://stackoverflow.com/questions/15510748/. I want to say, the less exotic mapping is used, the simplier usage of it we can achieve. – Radim Köhler Feb 20 '14 at 08:01

1 Answers1

0

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
}
Yogesh
  • 4,546
  • 2
  • 32
  • 41