JPA:返回多个实体的查询

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

有任何想法吗?

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

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

这是一个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 getLessonsWithProgress(@Param("userId") Integer userId, @Param("courseId")Integer courseId); 

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

 List 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); } 

输出@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 ] 

干杯

因为您要求JPA: Query that returns multiple entities ,所以EclipseLink也在它之下。 我在谷歌上搜索了EclipseLink这个问题。 所以这是我的解决方案。 希望对你有效。

 TypedQuery query = entityManager.createQuery("select p from Post p where p.publisher.pubId= :ID order by p.createdAt desc", Object[].class); query.setParameter("ID", publisherID); 

然后,您可以遍历结果对象并相应地转换它们。

 for (Object result : query.getResultList()) { myList.add((Post) result); } 

你也可以尝试这个,

 Query query = entityManager.createQuery("select p from Post p where p.publisher.pubId= :ID order by p.createdAt desc"); 

参考: http : //wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Querying/JPQL