Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

212
Vistas
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);
about 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

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.

about 4 years ago · Santiago Trujillo Denunciar

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

about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda