【问题标题】:Hibernate criteria query multiple criteriaHibernate条件查询多个条件
【发布时间】:2012-12-01 06:51:15
【问题描述】:

在我当前的项目中,我遇到了使用休眠条件查询获取实体的问题。我有以下实体:

  • Professor,其中包含学生列表
  • 学生,其中包含作业列表。
  • Assignment,其中包含分配给它的学生的 ID。

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

此查询显示了我想在条件查询中实现的内容。

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

如何使用休眠条件 API 实现此查询?

【问题讨论】:

    标签: java hibernate hibernate-criteria


    【解决方案1】:

    假设你的表格是这样的:

    @Entity
    public class Professor{
        K id;
        List<Student> students;
    }
    
    @Entity
    public class Student{
        K profid;
        List<Assignments> assignments;
    }
    
    @Entity
    public class 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();
    

    【讨论】:

    • 非常感谢您的回答!
    • 如果我想为professor.id 添加一个Restriction.eq 等于1234,即将属性直接与Long 进行比较,该怎么办?
    • @KevinMeredith Restrictions.eq("professor.id", 1234L)
    • 正在寻找这样的东西!很高兴这个解决方案在 3 年后仍然有效:D
    • createCriteria 已弃用。更新答案。
    猜你喜欢
    • 2012-05-01
    • 1970-01-01
    • 2011-04-26
    • 1970-01-01
    • 2013-10-01
    • 1970-01-01
    • 2015-01-11
    • 1970-01-01
    • 2016-09-06
    相关资源
    最近更新 更多