Appropriate Spring JPA method name to query a random string in SQL

To get a record in a SQL table with name

, I use the following query:

SELECT * FROM User WHERE User.name = name;

      

And the corresponding Spring JPA method name looks like this:

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

      

My question is this:

How can I query a random record from a SQL table?
I know my SQL query should be like this:

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

      

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

UserEntity findUserXXXXXXX (XXXXXXX);

      

+3


source to share


1 answer


JPA supports the features defined in the specification. You can use the native query

or option JPA 2.1 function

to call database functions that are not directly supported by the JPA specification. You can use annotation @Query

in your spring data 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 an individual user.

+3


source







All Articles