3
I am creating a REST API, using Spring Boot, which, using data from a table, displays random phrases.
Giving a Google, I found that it is possible to generate random results through pure SQL:
SELECT <coluna> FROM <tabela> ORDER BY RANDOM() LIMIT 1;
I made the appointment of Bank H2, which is the bank I’m using, and it worked:
The problem is that Spring Data does not recognize the SQL command LIMIT
. When I create the query inside the repository, through this code:
public interface QuoteRepository extends JpaRepository<Quote, Integer> {
@Query("SELECT detail FROM Quote ORDER BY RANDOM() LIMIT 1")
Quote findByQuote();
Quote findByActor(String actor);
}
I get the following exception:
Unexpected token: LIMIT near line 1, column 54 [SELECT Detail FROM Challenge. Quote ORDER BY RANDOM() LIMIT 1]
Observing: the table scripts is mapped by the domain class Quote
.
Does anyone know of a command they can replace LIMIT
?
Complete code on Github.
Marciano, thank you so much for answering! I only have one question: pagination needs to be an
list
? For the code you suggested to use onservice
, my method would have to returnresult
. The problem is that in the interfaceQuoteService
it has been established that the method should beQuote getQuote()
and, is implemented in the classQuoteServiceImpl
, must return a quote object, which means, in my understanding, not to return a list... Is there any way?– Van Ribeiro
Does not solve your problem iterating the list, feeding an object
Quote
with the record found and return thisQuote
in his method?– StatelessDev
@Statelessdev, I even tried to use it here, but I need the method to be
Quote findByName();
. The list that is being iterated is of the String type. Even if I useList<Quote> result
, will still be returning a list of type Quote and not a Quote object. I may be wrong, but this is how I understand the return of a method. The Interface came already created and precise followed the pattern of the project.– Van Ribeiro
Marciano, a person sent a documentation link of
Spring Data
and also that other answer, for the use ofnative queries
and the compiler accepted and the error. Now I’m having another problem... He’s not recognizing theid
... I think I’ll open up another question to that...– Van Ribeiro
Yes, open another question detailing the error.
– Marciano Machado
Seeking a solution, I found a question in the OR, using paging as you suggested, as you suggested, but using Page instead of Pageable. I will post the solution here, in case there are people with more problems. I adapted to my problem and worked and also, with this, solved the ID problem. Even so, thank you so much for your availability.
– Van Ribeiro
Just one more thing, in case someone is reading this answer and is considering using the constructor
PageRequest
, it has been discontinued. Instead, it can be usedPageRequest.of(int page, int size)
, as shown in the documentation.– Van Ribeiro