【问题标题】:How to get 5 latest posts using CrudRepository in Spring Boot如何在 Spring Boot 中使用 CrudRepository 获取 5 个最新帖子
【发布时间】:2018-04-14 01:10:25
【问题描述】:

我是 Spring Boot 的新手。我正在使用 Spring MVC 制作博客,但我不知道如何在内存数据库中获取 5 个最新帖子(我现在不想使用任何数据库,如 MySQL、MariaDB 等)。以下是我迄今为止创建的类。在 PostServicesImp 中,我创建了一个名为 findLatest5 的方法并在控制器中使用它,它运行良好。现在我想使用 CrudRepository 方法。感谢您阅读我的帖子 发帖

@Entity
public class Post {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;

    @Column(nullable=false, length=300)
    private String title;

    @Column(nullable=false)
    private String body;

    @ManyToOne(optional=false, fetch=FetchType.LAZY)
    private Users author;

    @Column(nullable=false)
    private Date date= new Date();

    public Post(){

    }

    public Post(Long id,String title, String body, Users author){
        this.id=id;
        this.title=title;
        this.body=body;
        this.author=author;
    }

    public Long getId() {
        return id;
    }

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

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }

    public Users getAuthor() {
        return author;
    }

    public void setAuthor(Users author) {
        this.author = author;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    @Override
    public String toString() {
        return "Post [id=" + id + ", title=" + title + ", body=" + body + ", author=" + author + ", date=" + date + "]";
    }
}

后存储库

public interface PostRepository extends CrudRepository<Post, Long>{
    List<Post> findById(Long id);
    List<Post> findByAuthor(String author);
}

邮政服务:

public interface PostServices {
    List<Post> findLatest5();
}

PostServicesImp

@Service
public class PostServicesImp implements PostServices{

    @Autowired
    private PostRepository pRepo;

    @Override
    public List<Post> findLatest5() {
//      return pRepo.findLatest5Posts(new PageRequest(0, 5));
        return posts.stream().sorted((a,b)-> b.getDate().compareTo(a.getDate()))
                .limit(5)
                .collect(Collectors.toList());
    }
}

【问题讨论】:

    标签: java spring spring-boot spring-data-jpa


    【解决方案1】:

    来自Spring Data JPA Documentation

    限制查询结果

    查询方法的结果可以通过关键字firsttop,可以互换使用。 可选数值可以 附加到 top/first 以指定最大结果大小 回来。如果省略数字,则假定结果大小为 1。

    例子:

    User findTopByOrderByAgeDesc();
    List<User> findTop10ByLastname(String lastname, Pageable pageable);
    

    因此,在您的情况下,将其添加到您的 PostRepository:

    List<Post> findTop5ByOrderByDateDesc();
    

    【讨论】:

    • 非常感谢。抱歉,由于在笔记本电脑前待了几个小时,我按错了按钮:D
    • 我不明白。哪个按钮?
    • 我的意思是我想点击向上箭头,但由于一些愚蠢的错误,我点击了向下按钮
    • 您还没有足够的声望来投票(您需要 15 分),但您可以接受答案。这将为您提供声望点,您将获得徽章。因此,请使用该答案旁边的检查选择哪个答案最能解决您的问题。这也将有助于未来有相同问题的用户快速找到合适的答案。
    【解决方案2】:

    您可能应该使用PagingAndSortingRepository 而不是CrudRepository。这使您可以更好地控制正在处理的数据集。

    PostRepository.java

    public interface PostRepository extends PagingAndSortingRepository<Post, Long> {
        List<Post> findById(Long id);
        List<Post> findByAuthor(String author);
    }
    

    PostServicesImp

    @Service
    public class PostServicesImp implements PostServices{
    
        @Autowired
        private PostRepository pRepo;
    
        @Override
        public List<Post> findLatest5() {
            return pRepo.findAll(new PageRequest(0, 5, new Sort(new Order(Direction.DESC, "whatever property you want to find the latest records based on"))));
        }
    }
    

    参考资料:

    https://docs.spring.io/spring-data/data-commons/docs/1.6.1.RELEASE/reference/html/repositories.html

    How to query data via Spring data JPA by sort and pageable both out of box?

    【讨论】:

      猜你喜欢
      • 2019-03-28
      • 2016-12-25
      • 2013-08-02
      • 2018-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-19
      相关资源
      最近更新 更多