[英]For a JPA entity with many to 1 relation to a data entity, how to sort a list of objects by the result of a method call of the data entity?
[英]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 獲取帖子。
請給我任何解決方案
@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.