1

I am a novice in Spring Boot. I am making a blog using Spring MVC, but I don't know how to get 5 latest posts in the in-memory database (I don't want to use any database like MySQL, MariaDB,etc right now). The following are classes that I have created so far. In the PostServicesImp, I created a method called findLatest5 and used it in the controllers, it works perfectly. Now I want to use CrudRepository methods. Thanks for reading my posts Post

@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 + "]";
    }
}

PostRepository

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

PostServices:

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());
    }
}
Juan Carlos Mendoza
  • 5,736
  • 7
  • 25
  • 50
Alice
  • 281
  • 1
  • 3
  • 20

2 Answers2

3

From the 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);

So in your case add this to your PostRepository:

List<Post> findTop5ByOrderByDateDesc();
Juan Carlos Mendoza
  • 5,736
  • 7
  • 25
  • 50
  • @HaVan please read: [What should I do when someone answers my question?](https://stackoverflow.com/help/someone-answers) – Juan Carlos Mendoza Nov 01 '17 at 22:02
  • Thanks you so much. Sorry, I pressed the wrong button, as a consequence of spending hours in front of the laptop :D – Alice Nov 01 '17 at 23:12
  • I didn't understand. Which button? – Juan Carlos Mendoza Nov 01 '17 at 23:21
  • I mean I wanted to click the up arrow but by some stupid mistakes, I clicked the down button – Alice Nov 01 '17 at 23:41
  • You don't have enough reputation to upvote yet (you need 15 pts), but you can accept an answer. This will give you reputation points and you will earn badges. So choose which answer best solves your problem using the check next to that answer. This also will be helpful for future users who can have the same question to find an appropriate answer quickly. – Juan Carlos Mendoza Nov 02 '17 at 00:10
  • Oh thanks, I am new to Stack Overflow. I thought you are upset because I somehow downvote your answer – Alice Nov 02 '17 at 00:36
1

You should probably use PagingAndSortingRepository instead of CrudRepository. This gives you better control over the data set you are dealing with.

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"))));
    }
}

References:

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?

Srikanth Anusuri
  • 1,234
  • 9
  • 16