简体   繁体   English

Spring Data JPA限制嵌套集合大小为Pageable

[英]Spring Data JPA limit nested collection size as Pageable

I'm using SpringBoot 2.0.4. 我正在使用SpringBoot 2.0.4。

The idea is to retrieve a Conversation entity that contains a collection of Message objects. 这个想法是检索一个包含Message对象集合的Conversation实体。 But I need a control over the size of messages collection eg retrieve only 20 latest or so. 但是我需要控制消息收集的大小,例如仅检索20个最新消息。

@Entity
public class Conversation {
    //fields...
    @OneToMany(cascade = CascadeType.ALL)
    private List<Message> messages = new ArrayList<>();
    //methods...
}

and

@Entity
public class Message {
    //....
}

So when I'm retrieving a conversation by Id like this: 因此,当我像这样通过ID检索对话时:

conversationRepository.findById(id)

How can I include only the x (eg 20) of latest messages? 如何仅包含x(例如20条)最新消息?

In the MessageRepository interface, add: MessageRepository界面中,添加:

@Query("select messages from Conversation c inner join c.messages messages where c = :conversation")
  public Page < Message > findByConversation(@Param("conversation") Conversation conversation, Pageable pageable);

To return the last 20 ( or even n ) records , you sort them by message id in descending order: 要返回最后20条(甚至n条)记录,请按消息ID降序对它们进行排序:

Pageable pageable = new PageRequest(0, 20, Sort.Direction.DESC, "id");
Page<Message> messages = repo.findByConversation(conversation, pageable); 
List<Message> last20MessageList = messages.getContent();

You can try this code for your case 您可以根据情况尝试使用此代码

Pageable pageable = new PageRequest(0, 20, Sort.Direction.DESC, "id");

Page<Message> lastPage = conversationRepository.findById(id, pageable);
// this is a list of the last 20 records
List<Message> latestMessage = lastPage .getContent();

Hope this help! 希望有帮助!

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

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