[英]How to use index column in many-to-many association in criteria in Hibernate?
我正在Java中使用Hibernate 3。
我的POJO类别如下:
教师
private long id;
private String teacherName;
private List<Student> students;
// getter-setter of all
学生.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包含id和studentName属性的映射。
我的数据库结构如下所示:
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
现在,我要按Student_position的顺序获取ID = 1的所有附加到Teacher的学生。
我写了以下标准:
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();
在这里, 学生将按主键1,2,3的顺序给我记录。
我希望这些记录按其Student_position为1,3,2的顺序排列。
我该如何实现?
Long techId=1l;
Criteria criteria = getSession().createCriteria(Student.class, "student");
criteria.add(Restrictions.eq("student.teacherId", techId));
criteria.addOrder(Order.asc("student.studentPosition"));
如果模型对象中不存在该字段,则无法使用条件查询对象。 您可以使用的其他方法是休眠本机查询。
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();
您可以添加排序条件org.hibernate.criterion.Order
criteria.addOrder( Order.asc("yourPropertyName"));
您还可以添加多个以上订购之一。 另请参阅此处的 15.3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.