簡體   English   中英

如何根據 jpa @query 方法中的嵌套實體屬性對數據進行排序

[英]how to sort data based on nested entity property in jpa @query method

我想根據發布日期排序帖子

public class UserProfile {
    
    @Id
    private Long profileId;

    @ManyToMany(cascade= {CascadeType.PERSIST},mappedBy="postedOnUserProfiles")
    private List<Post> posts=new ArrayList<Post>();
    
}
    
public class Post {
    
    @Id
    @GenericGenerator(name="gen4",strategy="sequence")
    @GeneratedValue(generator="gen4")
    
    
    @ManyToMany
    //@JoinColumn(name="profileId")
    @JoinTable(
              name = "postedOnUserProfiles", 
              joinColumns = @JoinColumn(name = "postId"), 
              inverseJoinColumns = @JoinColumn(name = "profileId"))
    private List<UserProfile> postedOnUserProfiles=new ArrayList<UserProfile>(); 

    private int shareCount=0;
    private int commentCount=0;
    
    private int likeCount=0;
    private int wowCount=0;
    private int heartCount=0;
    private int weepEyesCount=0;
    
    @OneToMany(cascade=CascadeType.ALL,orphanRemoval=true,fetch=FetchType.LAZY)
    private List<Comment> postComments=new ArrayList<Comment>();
    
    private Date publishDate=new Date();
}

@Repository
public interface UserProfileRepo extends JpaRepository<UserProfile, Long>{

    @Query(" SELECT posts  From UserProfile up  where up.profileId=:userProfileId order by up.posts.publishDate")
    public Page<Post> findPostByOfProfilePageable(long userProfileId,Pageable pageable);
}

我想根據 post.publishDate 獲取帖子。
請給我任何解決方案

  1. 您正在選擇帖子,而不是 userProfiles,因此該方法應位於 PostRepository
  2. 由於您的方法已經使用 Pageable,您可以在其中提供排序規則
@Query(" SELECT p From Post p where p.authorId=:userProfileId")
public Page<Post> findPostByOfProfilePageable(long userProfileId,Pageable pageable);

客戶:

postRepo.findPostByOfProfilePageable(prodileId, PageRequest.of(0, 20, Sort.by("punlishDate”));

使用java.util.Collections.sort()並為您的 Post class 實現類似的接口。

請參閱此處的示例: https://www.baeldung.com/java-comparator-comparable

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM