【问题标题】:Hibernate query : retrieve rows from the many side matching with one side休眠查询:从与一侧匹配的多侧检索行
【发布时间】:2013-10-04 17:54:24
【问题描述】:

我在使用休眠从数据库中检索记录时遇到问题。这是这种情况。 我有 3 个班级(还有 3 个表格)。

这些是我的课。

Exam
-----
Integer exam_id
String exam_name

Subject
-------
Integer subject_id,
String subject_name

Scores
-------
Exam exam,
Subject subject,
Integer score

这是我的桌子

Exam
-----
exam_id,
exam_name

Subject
-------
subject_id,
subject_name

Scores
-------
exam_id,
subject_id,
score

我想做的是,我想检索科学科目的所有分数。我认为可以使用这个 sql 查询来做到这一点。

select sc.* from Scores sc inner join subject su on sc.subject_id=su.subject_id where su.subject_name= "science"。

但我想知道存档的最佳方式。是否可以使用“标准”来做到这一点?或任何其他最好的方法?请指导我。

谢谢

【问题讨论】:

    标签: hibernate hql


    【解决方案1】:

    是的,您可以使用条件,但使用简单的 HQL 查询更简单。

    CriteriaBuilder cb = em.getCriteriaBuilder();   //em is the entity manager
    
    CriteriaQuery<Scores> criteriaQuery = cb.createQuery(Scores.class);             
    Root<Scores> scoreRoot = criteriaQuery.from(Scores.class);
    
    Subquery<Integer> subquery = criteriaQuery.subquery(Integer.class);
    Root root = subquery.from(Subject.class);
    
    subquery.select(root.get("subject_id"));
    subquery.where(cb.equal(root.get("subject_name"), "science"));
    
    criteriaQuery.where(cb.equal(scoreRoot.get("subject_id"),subquery));
    
    TypedQuery<Score> query = em.createQuery(criteriaQuery);
    
    return query.getResultList(); //this is the result
    

    这是使用标准。

    【讨论】:

      【解决方案2】:

      Hibernate 是一种 ORM 技术。如果你有这样的 PK/FK 相关表,你应该通过 XML 配置或基于注解的映射告诉 Hibernate。然后您可以通过类似这样的 HQL 查询获得结果;

      from Scores sc where sc.subject.subjectName="science"
      

      我假设 Scores 表和 Subject 表通过 subject_id 列相关。所以,你的课程应该是这样的;

      class Scores{
        Subject subject;
        Exam exam;
        int score;
      
        // getters and setters
      }
      
      class Subject{
        int subjectId;
        String subjectName;
      
       // getters and setters
      }
      
      class Exam{
        int examId;
        String examName;
      
       // getters and setters
      }
      

      然后就可以通过Scores对象的subject字段来获取分数了。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多