[英]JPA: Query that returns multiple entities
我正在編寫一個連接三個表的JPQL查詢。 在我的結果列表中,我想獲得每個匹配行的所有三個實體(希望這是有意義的)。
有任何想法嗎?
Hibernate 3.x是我的JPA提供者。
IIRC,你可以做一個SELECT o1, o2, o3 FROM EntityA o1, EntityB o2, EntityC o3 WHERE ....
,結果將是一個List<Object[3]>
,其中數組內容將包含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<Object[]> getLessonsWithProgress(@Param("userId") Integer userId, @Param("courseId")Integer courseId);
然后,我調用此方法並打印結果:
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);
}
輸出@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 ]
干杯
如果多對一或一對多關系如何獲得其中一個實體的多個記錄? 假設A是一個實體,B是另一個實體,但它們有一對多關系,當你得到結果時,你期望B有一條記錄而A有超過1條記錄? 我的查詢如下,但我不知道如何獲得第二個實體的多個記錄?
@Query("SELECT wl, gr FROM WatchList as wl, GeozoneReference gr " +
"WHERE wl.watchlistId = gr.objWatchList.watchlistId " +
"AND wl.watchlistId =:watchlistId")
List<Object[]> findWatchlistByWatchlistId(@Param("watchlistId") Long watchlistId);
因為您要求JPA: Query that returns multiple entities
,所以EclipseLink也在其中。 我在谷歌搜索EclipseLink時遇到了這個問題。 所以這是我的解決方案。 希望對你有效。
TypedQuery<Object[]> 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.