Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

210
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!