JPA:返回多个实体的查询

Jus*_*ble 32 java hibernate jpa jpql

我正在编写一个连接三个表的JPQL查询.在我的结果列表中,我想获得每个匹配行的所有三个实体(希望这是有意义的).

有任何想法吗?

Hibernate 3.x是我的JPA提供者.

Tas*_*kos 42

IIRC,你可以做一个SELECT o1, o2, o3 FROM EntityA o1, EntityB o2, EntityC o3 WHERE ....,结果将是a List<Object[3]>,其中数组内容将包含o1,o2,o3值.

  • @John:另外,你可以从hql调用构造函数,所以你也可以`选择新的Foo(o1,o2,o3)...`并得到List <Foo>而不是List <Object []>. (6认同)
  • 好的,但是如果我想使用JPA TypedQuery怎么办:myEntityManager.createQuery("select o1,o2 ...",<要放什么?>) (4认同)

Cas*_*rin 24

这是一个Spring Data示例,但它在JPA中的工作方式相同

//HQL query
 @Query("SELECT c,l,p,u FROM  Course c, Lesson l, Progress p, User u "
            + "WHERE c.id=l.courseId AND l.id = p.lessonId AND p.userId = u.id AND u.id=:userId AND c.id=:courseId")
    public List<Object[]> getLessonsWithProgress(@Param("userId") Integer userId, @Param("courseId")Integer courseId);
Run Code Online (Sandbox Code Playgroud)

然后,我调用此方法并打印结果:

List<Object[]> lst = courseRepository.getLessonsWithProgress(userId, courseId);
for (Object o[] : lst) {
    Course c = (Course) o[0];
    Lesson l = (Lesson) o[1];
    Progress p = (Progress) o[2];
    User u = (User) o[3];
    //all the classes: Course, Lesson, Progress and User have the toString() overridden with the database ID;    
    System.out.printf("\nUser: %s \n Lesson: %s \n Progress: %s \n Course: %s",u,l,p,c);
}
Run Code Online (Sandbox Code Playgroud)

输出@Test在这里:

User: com.cassio.dao.model.User[ id=1965 ] 
Lesson: com.cassio.dao.model.Lesson[ id=109 ] 
Progress: com.cassio.dao.model.Progress[ id=10652 ] 
Course: com.cassio.dao.model.Course[ id=30 ]
Run Code Online (Sandbox Code Playgroud)

干杯