问题描述
我想根据发布日期对帖子进行排序
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 获取帖子。
请给我任何解决方案
解决方法
- 您选择的是帖子,而不是 userProfiles,因此该方法应该在 PostRepository 中
- 由于您的方法已经使用了 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 类实现类似的接口。