Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

215
Visualizações
Corresponding Spring JPA method name for requesting a random row in SQL

In order to get the a record in an SQL table with a name, I am using the following query:

SELECT * FROM User WHERE User.name = name;

And the corresponding Spring JPA method name is the following:

UserEntity findUserByName(@Param("name") String name);

My question is the following:

How can I request a random record from an SQL table?
I know that my SQL query should be the following:

SELECT * FROM User
ORDER BY RAND()
LIMIT 1;

But, what should be the corresponding Spring JPA method name for that?

UserEntity findUserXXXXXXX (XXXXXXX);
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

JPA supports functions which are defined in specification. You can use native query option or JPA 2.1 function to call database functions which are not directly supported by the JPA specification. You can use @Query annotation in your spring data jpa repository.

Native Query

@Query(value="SELECT * FROM User ORDER BY RAND() LIMIT 1", nativeQuery = true)
UserEntity findUser();

Function

@Query("SELECT u FROM UserEntity u order by function('RAND')")
List<UserEntity> findUser();

You can use list.get(0) to get the single user.

over 4 years ago · Santiago Trujillo Relatório

0

if you want to random a list you can easily do it by using PagingAndSortingRepository and provide a random page number where (page_number < page_count)

e.g

long page_count = (totalRecords / perPage)
//Use PageRequest for PagingAndSortingRepository Pageable object
PageRequest.of(new Random().nextLong(page_count), perPage)

or you can provide the random page number from front_end side

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda