Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get last records ordered by date on Spring Data

I'm trying to define a method in a Spring Data repository to fetch the last records on a table ordered by date. This is my entity:

@Entity public class News {      @Id     @GeneratedValue     private Long id;      @Column(nullable = false)     private String title;      @Column(nullable = false)     private String text;      private Date publicationDate;      /* Getters and Setters */ } 

And this is my repository:

public interface NewsRepository extends JpaRepository<News, Long> {     List<News> findFirst5OrderByPublicationDateDesc(); } 

If I try to use launch the project I get the next error:

Caused by: org.springframework.data.mapping.PropertyReferenceException: No property desc found for type Date! Traversed path: News.publicationDate.

And if I remove the Desc I get this:

Caused by: java.util.NoSuchElementException

What I'm doing wrong?

like image 964
David Moreno García Avatar asked Dec 19 '14 13:12

David Moreno García


People also ask

How do I Sort by date in JPA repository?

Data JPA provides Sorting support out of the box. To add Sorting support to our Repositories, we need to extend the PagingAndSortingRepository<T, ID> interface rather than the basic CrudRepository<T, ID> interface. List<Laptop> findAll(Sort sort); Returns a sorted list of laptops.

How do you get data in descending order in spring boot?

One option is to use Spring Data's method derivation, whereby the query is generated from the method name and signature. All we need to do here to sort our data is include the keyword OrderBy in our method name, along with the property name(s) and direction (Asc or Desc) by which we want to sort.

How do you Sort data in spring?

In Spring Data JPA query results can be sorted in two ways: using an ORDER BY clause in a JPQL query. adding a parameter of type Sort to the query method.

What does @table do in spring?

The @Table annotation allows you to specify the details of the table that will be used to persist the entity in the database. The @Table annotation provides four attributes, allowing you to override the name of the table, its catalog, and its schema, and enforce unique constraints on columns in the table.


1 Answers

Turns out that the signature of the method was incorrect. The right one is:

findFirst5ByOrderByPublicationDateDesc() 

Is a little confusing because in the official samples they have this:

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

As you can see there is only one By there, the usual one.

like image 84
David Moreno García Avatar answered Sep 23 '22 07:09

David Moreno García