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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With