Reputation: 3576
In springboot you can have a repository that extends JpaRepository<User, String>
Now if you want to write a query to that repository, you can write multiple findBy queries such as:
User findByUsername(String username);
User findByFirstName(String firstName);
User findByFirstNameAndLastName(String firstName, String lastName);
then you need matching controllers like:
@RequestMapping(value = "/users/{username}" , method = RequestMethod.GET)
public @ResponseBody List<User> getUser(@PathVariable("username") String username) {
return userService.findByUsername(username);
}
etc, etc...
I don't want to have to write every single findBy for each combination of elements and create all the matching controllers like that.
So what I want to know is how you can search by a whole object. For example posting something like
{
"username":"freddy"
}
will search by username and equally
{
"firstName":"Fred",
"lastName":"Doe"
}
will search by first and last name.
Is there a way to write both a JpaRepository method and a controller that can take a (in this case) User object with any combination of fields, and perform a search for that?
Thanks.
Upvotes: 0
Views: 10520
Reputation: 7394
You can try JPA's Query by Example. JpaRepository
extends another interface named QueryByExampleExecutor
, which has a quite a few methods for searching by example. Here is a simple example,
// here the first name, last name, and username may be null
// or not null. Make sure that they are not all at the same time
String firstName = "James";
String lastName = null;
String userName = "jbond";
Example<User> example = Example.of(new User(firstName, lastName, username));
Iterable<User> = repository.findAll(example);
You can do other fancy stuff. Here is an example.
Q. Is there a way to return unique result fields? So in that example, passing firstName would return a unique list of all the lastNames and all the possible userNames
For this type of situations, I haved used native queries. Here is an example,
@Query(value = "SELECT DISTINCT u.lastName FROM User u WHERE u.firstName = ?1",
nativeQuery = true)
List<String> findDistinctLastName(String firstName);
Upvotes: 2