简体   繁体   中英

How to use index column in many-to-many association in criteria in Hibernate?

I'm using Hibernate 3 with Java.

My POJOs classes are as follows:

Teacher.java

private long id;
private String teacherName;
private List<Student> students;
// getter-setter of all

Student.java

 private long id;
 private String studentName;

// getter-setter of both

Teacher.hbm.xml

<class name="Teacher" table="teacher_master">
    <id name="id" column="id" type="long">
        <generator class="native"></generator>
    </id>

    <property column="teacher_name" name="teacherName" type="string" />

    <list name="students" cascade="refresh">
        <key column="teacher_id"/>
        <index column="student_position" type="integer"/>
        <one-to-many class="Student"/>
    </list>
</class>

Student.hbm.xml contains mappings for id & studentName properties.

My database structure looks like the following:

teacher_master

id  | teacher_name
----|--------------
1   | teacher1
2   | teacher2

student_master

id  | student_name  | teacher_id  | student_position
----|---------------|-------------|------------------
1   | student1      |      1      |      0
2   | student2      |      1      |      2
3   | student3      |      1      |      1

Now I want to fetch all Students attached to Teacher with id = 1, in the order of student_position .

I've written the following criteria:

List<Long> ids = new ArrayList<Long>();
ids.add(1l);
ids.add(2l);
ids.add(3l);
Criteria criteria = session.createCriteria(Student.class);
criteria.add(Restrictions.in("id", ids));
List<Student> students = criteria.list();

Here students will give me the records in order of the primary key that is 1,2,3.

I want these records to be in order of their student_position that is 1,3,2.

How can I achieve this?

     Long techId=1l;
     Criteria criteria = getSession().createCriteria(Student.class, "student");
     criteria.add(Restrictions.eq("student.teacherId", techId));
     criteria.addOrder(Order.asc("student.studentPosition"));

You cant query for object with criteria If the field is not present in the model object. The Other way you can go with is hibernate native query.

    Long techId=1l;
    Query query = session.createSQLQuery(
           "select * from student_master s where s.teacher_id = :teacherId order by s.student_position")
            .addEntity(Student.class)
            .setParameter("teacherId", "techId");
             List result = query.list();

You can add an ordering criterion, org.hibernate.criterion.Order

criteria.addOrder( Order.asc("yourPropertyName"));

You can also add more than one of these orderings. Also see here under 15.3

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM