简体   繁体   English

JPQL选择所有对象,但对对象集合使用setMaxResult

[英]JPQL select all objects, but setMaxResult on object collections

I have 3 entities: 我有3个实体:

User which has Set galleries. 拥有画廊的用户。 Gallery which has Set photos. 设有照片集的画廊。

Now I want to select all users with their last 3 photos by created time(User may have 10 galleries and 100 photos for each gallery). 现在,我想按创建时间选择所有用户及其最后3张照片(用户可能有10个画廊,每个画廊可能有100张照片)。 How can I do the jpql? 我该如何做jpql?

I don't know how to get the top 3 photos(select top 3 from p) below: 我不知道如何获取下面的前3张照片(从p中选择前3张照片):

Query q = em.createQuery("select u, (select top 3 from p) from User u left join u.galleries g left join g.photos p"); 查询q = em.createQuery(“从用户u中选择u, (从p中选择前3个) u左连接u。图库g左连接g.photos p”);

I know I can get only one user with top 3 photos by: 我知道我只能通过以下方式获得前三张照片的用户:

Query q = em.createQuery("select u, p from User u left join u.galleries g left join g.photos p where u.id =:userId").setMaxResults(3); 查询q = em.createQuery(“从用户中选择u,p从用户u左连接u。图库g左连接g.photos p,其中u.id =:userId”)。setMaxResults(3);

But what about all users in one jpql? 但是一个jpql中的所有用户呢?

Thanks in advance. 提前致谢。

You you happen to work on PostgreSQL you can use a window function to select the first 3 photo.ids by user: 您碰巧在PostgreSQL上工作时,可以使用窗口函数按用户选择前3个photo.id:

List<Long> photoIds = (List<Long>)
    em.createNativeQuery(
    "select data.p_id
        from 
        (
            SELECT p.id as p_id, row_number() as rw OVER w as rw
            FROM photo p
            INNER JOIN galley g on g.id = p.galery_id
            INNER JOIN user u on u.id = g.user_id
            WINDOW w AS (PARTITION BY u.id ORDER BY p.creation_time DESC)
        ) data 
        where rw <= 3", Long.class)
.getResultList(); 

Then with these ids you can fetch the photo/gallery/user: 然后使用这些ID,您可以获取照片/图库/用户:

List<Photo> photos = (List<Photo>)
    em.createQuery(
    "select p
    from Photo p
    join fetch p.gallery g
    join fetch g.user u
    where p.id in (:photoIds)")
.setParameter("photoIds", photoIds) 
.getResultList();

You can then recreate the user/gallery/photo back from the Photo list. 然后,您可以从“照片”列表重新创建用户/画廊/照片。

There is no other way to use JPQL to only select partial views over a joined collection of children entities. 没有其他方法可以使用JPQL在已联接的子实体集合上选择部分视图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM