gpt4 book ai didi

java - 如何在 Spring Boot 中使用 CrudRepository 获取 5 个最新帖子

转载 作者:行者123 更新时间:2023-11-29 04:24:30 24 4
gpt4 key购买 nike

我是Spring Boot的新手。我正在使用 Spring MVC 创建博客,但我不知道如何在内存数据库中获取 5 个最新帖子(我现在不想使用任何数据库,如 MySQL、MariaDB 等)。以下是我到目前为止创建的类。在 PostServicesImp 中,我创建了一个名为 findLatest5 的方法并在 Controller 中使用它,它运行良好。现在我想使用 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());
}
}

最佳答案

来自Spring Data JPA Documentation :

Limiting query results

The results of query methods can be limited via the keywords first or top, which can be used interchangeably. An optional numeric value can be appended to top/first to specify the maximum result size to be returned. If the number is left out, a result size of 1 is assumed.

Examples:

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

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

List<Post> findTop5ByOrderByDateDesc();

关于java - 如何在 Spring Boot 中使用 CrudRepository 获取 5 个最新帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47059572/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com