【问题标题】:Hibernate Mapping Through Another Entity通过另一个实体的休眠映射
【发布时间】:2011-01-15 01:43:59
【问题描述】:

考虑这个简单的数据库架构:

 User                Course              StudentCourse       Student
+-------------+     +-------------+     +-------------+     +-------------+
| -user_id    |1   *| -course_id  |1   *| -course_id  |*   1| -student_id |
|             |---->| -user_id    |---->| -student_id |---->|             |
+-------------+     +-------------+     +-------------+     +-------------+

[1   *] = 1 to many relationship 

我为 User、Course 和 Student 对象创建了实体,并设置了以下映射:

User   -> Course  - one to many
Course -> Student - many to many

在我的 Java 类中,我可以通过调用 user.getCourses() 访问用户的课程,并且我可以通过调用 course.getStudents() 访问课程中的所有学生。 我希望能够找到特定用户教授的所有课程中的所有学生,例如 user.getCourse().getStudents(),但是因为 user.getCourses() 返回 Collection<Course> 我无法在收藏。 我应该如何使用 Hibernate 实现这一点?命名查询是我唯一的选择吗?

【问题讨论】:

    标签: java database hibernate jpa orm


    【解决方案1】:

    我猜你必须在 Course 中定义 fetchType = EAGER,这实际上不是一个好主意 所以 HQL 会是最好和最有效的。

    【讨论】:

      【解决方案2】:

      你说

      我希望能够找到由特定用户教授的所有课程中的所有学生

      使用 HQL 查询

      SELECT DISTINCT _student FROM User AS _user, IN ( _user.courses ) _course, IN( _course.students ) _student WHERE _user.id = :id
      

      SELECT DISTINCT _student FROM User _user inner join _user.courses _course inner join _course.students _student WHERE _user.id = :id
      

      问候,

      【讨论】:

        【解决方案3】:

        您可以执行以下操作:

        List<Student> students = new ArrayList<Student>();
        for ( Course course : user.getCourses() )
        {
            students.addAll( course.getStudents() );
        }
        

        但是这会非常低效(请参阅“SELECT N+1”问题)

        我还没有机会测试它,但您的命名查询应该是这样的: "SELECT c.students FROM Course c WHERE c.user.name = 'username'"

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-11-11
          • 2019-12-03
          • 2020-12-18
          • 1970-01-01
          • 1970-01-01
          • 2016-10-18
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多