Spring mongo存储库按特定属性降序排序

时间:2018-02-05 16:14:29

标签: spring mongodb spring-data

我想通过lastChange属性对mongo的项目列表进行Descending排序。

RequestRepository接口:

public interface RequestRepository extends MongoRepository<Request, String> {
    List<Request> findByUser(String id);
}

Request.java:

@Document(collection = "Requests")
public class Request {

@Id
private String id;
private String user;
private String username;
private String requestTitle;
private String requestMessage;
private boolean read;
private Date lastChange;
private Date requestDate;
private boolean isActiveRequest;
private boolean isPremiumRequest; //paid request

public Request() {}

public Request(
        String user,
        String requestTitle,
        String requestMessage,
        boolean read,
        Date lastChange,
        Date requestDate,
        boolean isActiveRequest) {
    this.user = user;
    this.requestTitle = requestTitle;
    this.requestMessage = requestMessage;
    this.read = read;
    this.lastChange = lastChange;
    this.requestDate = requestDate;
    this.isActiveRequest = isActiveRequest;
}

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getUser() {
    return user;
}

public void setUser(String user) {
    this.user = user;
}

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public String getRequestTitle() {
    return requestTitle;
}

public void setRequestTitle(String requestTitle) {
    this.requestTitle = requestTitle;
}

public String getRequestMessage() {
    return requestMessage;
}

public void setRequestMessage(String requestMessage) {
    this.requestMessage = requestMessage;
}

public boolean isRead() {
    return read;
}

public void setRead(boolean read) {
    this.read = read;
}

public Date getLastChange() {
    return lastChange;
}

public void setLastChange(Date lastChange) {
    this.lastChange = lastChange;
}

public Date getRequestDate() {
    return requestDate;
}

public void setRequestDate(Date requestDate) {
    this.requestDate = requestDate;
}

public boolean isActiveRequest() {
    return isActiveRequest;
}

public void setActiveRequest(boolean activeRequest) {
    isActiveRequest = activeRequest;
}

public boolean isPremiumRequest() {
    return isPremiumRequest;
}

public void setPremiumRequest(boolean premiumRequest) {
    isPremiumRequest = premiumRequest;
}
}

在我的代码中,我有以下列表:

List<Request> = RequestRepository.findByUser(userObj.getId());

我希望RequestRepository.findByUser(userObj.getId());的数据按属性lastChange排序DESCENDING。

我在StackOverflow上搜索过,发现了以下排序方法:

List<Request> findAllByOrderByUpdatedAtDesc();

但如果我按用户搜索,则无效。

按用户ID搜索并按lastChange排序的解决方案是什么?

谢谢!

1 个答案:

答案 0 :(得分:1)

这应该这样做。

List<Request> findByUserOrderByLastChangeDesc(String user);

使用适当的详细信息更新您的问题。