0

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.

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.