【发布时间】: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