Spring Boot – Extending JPA Repository

Extending JPA Repository

In the last chapter, we wrote methods to return list of items. We also wrote a method to get an item by id. For example, we have

  • getPostById
  • getUserByID
  • getLocationById

Now what if we also want to get list of items based on other criteria. For example we want to:

  • get Users with the same lastname
  • get User based on an email address
  • get user where firstname like a given string
  • get Posts by date etc.

Let’s see how we can do all of these

 

The findBy<VariableName> method

This is a generic method implemented in Spring Data JPA. The VariableName is the member variable you want to search by. So In case of the User class, you can use:

  • findById,
  • findByFirstname
  • findByLastname
  • findByLocation
  • findByEmail

To use any of these, you simply need to define, it in the repository interface you created.

 

For now, let’s do this for the Location class. We would define findByName in the LocationRepository. Then we can use it in the LocationService and LocationController classes.

So in the LocationRepository, add the following line:

 

public List<Location> findByName(String name);

 

In the LocationService, write the following line:

 

//returns list of locations base on a given name
public List<Location> getLocationsByName(String name) {
    List<Location> locations  = new ArrayList<>();
	   
    locationRepository.findByName(name)
    .forEach(locations::add);
	   
    return locations;
}

 

Then, in the LocationController file, write the following line:

 

 @RequestMapping(value = "/locations/name/{name}")
 public List<Location> getLocationByName(@PathVariable String name) {
 	return locationService.getLocationsByName(name);
 }

 

Notice the RequestMapping in the getLocationByName method in the LocationController. You can see it has a value of /locations/name/{name}. This is so that it can be distinguished from the getLocation method which have similar RequestMapping.

 

I recommend you try every bit of this lesson yourself. If you have any challenges, then leave a comment below.

Next, we would examine Query Methods.