Skip to content

Problem when using Sort.by #3721

Closed as not planned
Closed as not planned
@oungsi2000

Description

@oungsi2000

this is my whole code
https://github.com/oungsi2000/jump-to-springboot

When I use JpaRepository with Sort.by and Pageable, I got some mismatch with this.

com.ll.jumptospringboot.domain.Answer.AnswerService.getList

public Page<Answer> getList(Question question, int page, String sortBy) {
        List<Sort.Order> sorts = new ArrayList<>();
        if (Objects.equals(sortBy, "mostVoted")) {
            sorts.add(Sort.Order.desc("voter"));
            sorts.add(Sort.Order.desc("createDate"));
            Pageable pageable = PageRequest.of(page,10, Sort.by(sorts));
            return this.answerRepository.findAllByQuestion(question, pageable);
        } else {
            sorts.add(Sort.Order.desc("createDate"));
            Pageable pageable = PageRequest.of(page,10, Sort.by(sorts));
            return this.answerRepository.findAllByQuestion(question, pageable);
        }
    }

com.ll.jumptospringboot.domain.Answer.Answer

public class Answer {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(columnDefinition = "TEXT")
    private String content;

    @Column(length = 200)
    private String title;

    private LocalDateTime createDate;

    @ManyToOne
    private Question question;

    @ManyToOne
    private SiteUser author;

    private LocalDateTime modifyDate;

    @ManyToMany
    Set<SiteUser> voter;
}

when using 'sorts.add(Sort.Order.desc("voter"));', If there are two or more voters, this.a
nswerRepository.findAllByQuestion(question, pageable); -> this doesn't get all Answers, instead gets pagination - 1 Answers

this is the result when the code above 'if (Objects.equals(sortBy, "mostVoted"))~~' executed
asdfad

this is the result when the code above 'else~~' executed
스크린샷 2024-12-18 오후 8 39 05

both counts should be same because the count means "All Answers" and it gets from same DB, same Hibernate query.
the difference between those is only 'sorts.add(Sort.Order.desc("voter"));' and attribute voter is @manytomany.
It is more strange that when the Entity Answer gets only one voter attribute, it works perfectly(both count is same) but when it gets two or more voter attribute, it just returns 9, not all of All Answers.

Please Help
If my English is Bad, I'm sorry. If you need extra explanation, Please notify me.

Metadata

Metadata

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions