Hibernate标准查询多个条件

Hibernate标准查询多个条件

本文介绍了Hibernate标准查询多个条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我目前的项目中,我遇到了使用hibernate标准查询获取实体的问题。我有以下实体:


  • 教授,其中包含学生列表

  • 学生,其中包含分配列表。

  • 分配,其中包含分配给其的学生的ID。



现在,我想要获得与教授相关的所有作业,即分配给他的学生的所有作业教授。

这个查询显示了我想要实现的内容标准查询。

  select * from Assigment p,Student a,Professor c其中p.studentid = a.id和a.proffid = c.id和c.id = 2411; 

如何使用hibernate标准API实现此查询?

  @Entity 
公开课教授{
K id;
列表< Student>学生们;
}

@实体
公共类学生{
K profid;
列表< Assignments>任务;
}

@实体
公共类赋值{
K studentid;

使用别名的简单示例:

  Criteria criteria = currentSession.createCriteria(Professor.class,professor); 
criteria.createAlias(professor.students,student);
criteria.createAlias(student.assigments,assigment);
criteria.add(Restrictions.eqProperty(professor.id,student.profid));
criteria.add(Restrictions.eqProperty(assigment.studentid,student.profid));
criteria.add(Restrictions.eq(id,2411));
return criteria.list();


In my current project I've faced a problem of getting entities with hibernate criteria query. I have the following entities:

  • Professor, which contains a list of students
  • Student, which contains a list of assignments.
  • Assignment, which contains id of student to which it is assigned to.

Now, I want to get all assignments relative to the professor, i.e. all assignments Professor assigned to his students.

This query shows what I want to implement in criteria query.

select * from Assigment p, Student a, Professor c where p.studentid = a.id and a.proffid = c.id and c.id = 2411;

How can I implement this query using hibernate criteria API?

解决方案

suppose your tables like that:

@Entity
public class Professor{
    K id;
    List<Student> students;
}

@Entity
public class Student{
    K profid;
    List<Assignments> assignments;
}

@Entity
public class Assignments{
    K studentid;
}

simple sample by using alias:

Criteria criteria = currentSession.createCriteria(Professor.class, "professor");
    criteria.createAlias("professor.students", "student");
    criteria.createAlias("student.assigments", "assigment");
    criteria.add(Restrictions.eqProperty("professor.id", "student.profid"));
    criteria.add(Restrictions.eqProperty("assigment.studentid", "student.profid"));
    criteria.add(Restrictions.eq("id", 2411));
return criteria.list();

这篇关于Hibernate标准查询多个条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 22:35