Abder KRIMA
Abder KRIMA

Reputation: 3688

How to get recent record by a field and ordered by date (complex query)?

I am trying to write a method in spring data to get last recod by text and ordered by updateDate.

My entity look like :

@Entity
public class Command {

    @Id
    @GeneratedValue
    private Long id;

    @Column(nullable = false)
    private String text;

    // epoch date
    private Long updateDate;

    /* Getters and Setters */
}

And this is the repository:

public interface CommandRepository extends JpaRepository<Command, Long> {
    Command findByTextAndTopByUpdateDateDesc(String text);
}

Of course, find by text method must give me more thant one reocord but by filtering with top date will get only one record !

the methode above return the following error :

Caused by: org.springframework.data.mapping.PropertyReferenceException: No property TopByUpdateDateDesc found for type Command! at org.springframework.data.mapping.PropertyPath.(PropertyPath.java:94)

I tried to check some stackoverflow postes to find any solution but nada !

Is there any solution to that case or i have to use native query ?

Upvotes: 0

Views: 114

Answers (1)

M. Deinum
M. Deinum

Reputation: 125158

The ordering in your query method is wrong. You first need the limitations (Top/First) before you do the where part and you end with the ordering. This is also what the error, given a bit cryptic, is telling you.

Instead of findByTextAndTopByUpdateDateDesc you should use something like findFirstByTextOrderByUpdateDateDesc.

The ordering etc. is explained in the Spring Data JPA documentation.

Upvotes: 1

Related Questions