Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring data repository's method to find by the field of a field

Tags:

I've two entities, a user and a registered user.

A registered user has a field of type user. I would like to have a method in the spring data repository related to this registered user entity to search all registered users by the username of the user that is connected to the registered user.

So, this is the registered user entity with an associated user field:

@Entity public class RegisteredUser implements Serializable {      ...      @OneToOne     @JoinColumn(name = "USERNAME_FK")     private User user;     ... } 

and this is a user with a username:

@Entity public class User implements Serializable {      ...     @Id     @Column(nullable = false)     protected String username;     ... } 
like image 408
nbro Avatar asked May 12 '16 17:05

nbro


People also ask

What does @repository do in Spring?

Spring @Repository annotation is used to indicate that the class provides the mechanism for storage, retrieval, search, update and delete operation on objects.

What is query method in Spring data?

Query methods are methods that find information from the database and are declared on the repository interface. For example, if we want to create a database query that finds the Todo object that has a specific id, we can create the query method by adding the findById() method to the TodoRepository interface.

What is difference between JpaRepository and CrudRepository?

CrudRepository provides CRUD functions. PagingAndSortingRepository provides methods to do pagination and sort records. JpaRepository provides JPA related methods such as flushing the persistence context and delete records in a batch.


1 Answers

Spring Data (at least 1.12.x version) uses PropertyPath#from method to extract path to a property for a predicate constructed from method name. According to sources it uses underscore as "field separator". So first variant is as follows

public interface RegisteredUserRepository extends CrudRepository<RegisteredUser,String> {     List<RegisteredUser> findRegisteredUserByUser_Username(String username); } 

There is also code which treat an uppercase char as field separator if whole field name is not found. So if you don't have a userUsername field in RegisteredUser second varian is

public interface RegisteredUserRepository extends CrudRepository<RegisteredUser,String> {     List<RegisteredUser> findRegisteredUserByUserUsername(String username); } 
like image 59
Ilya Avatar answered Sep 17 '22 17:09

Ilya