Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 506
Celik Avatar asked Apr 07 '17 21:04

Celik


People also ask

How do I get random rows in SQL?

To get a single row randomly, we can use the LIMIT Clause and set to only one row. ORDER BY clause in the query is used to order the row(s) randomly. It is exactly the same as MYSQL. Just replace RAND( ) with RANDOM( ).

Which method is used to fetch all rows in Spring Data JPA repository?

I can use the findAll() method to select * from my_table to get all columns and rows.

What are three methods to execute queries in JPA?

There are three basic types of JPA Queries:Query, written in Java Persistence Query Language (JPQL) syntax. NativeQuery, written in plain SQL syntax. Criteria API Query, constructed programmatically via different methods.

Can we write SQL query in JPA?

We can create a SQL query with the @Query annotation by following these steps: Add a query method to our repository interface. Annotate the query method with the @Query annotation, and specify the invoked query by setting it as the value of the @Query annotation's value attribute.


1 Answers

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.

like image 161
abaghel Avatar answered Oct 27 '22 23:10

abaghel