Search code examples
javaspring-bootapijpapath-variables

JPA Repository search by custom field


I am trying to get a list of the objects with the same field.

I have a model named Song, with the fields: name, genre, artist and id.

I read online about how to implement the method in the repository and i added it like this:

@Repository public interface ISongRepository extends JpaRepository<Song, Long>{

    @Query("SELECT s.name FROM Song s WHERE s.genre = ?1")
    Song findByGenre(String genre); 
}

Now i want to retrieve the objects with an endpoint that i create in the controller. But i can't find online how i need to correctly write this method.

I tried to use the same format as my get by id but that doesn't work, is there a different format when it comes to custom methods?

Code of my get by id:

@GetMapping(value = "/{id}")
@ResponseBody
public ResponseEntity getSongById(@PathVariable("id") Long id) {
    Optional<Song> song = songRepository.findById(id);

    if(song.isEmpty()) {
      return ResponseEntity.badRequest().body(song);
    }
    return ResponseEntity.ok(song.get());
}

Code of my method to retrieve the output of the custom method:

@GetMapping(value = "/genre/{genre}")
    @ResponseBody
    public ResponseEntity getSongByGenre(@PathVariable("genre") String songGenre){
        List<Song> song = song.(songRepository.findByGenre(songGenre));

        if(song.isEmpty()){
            return ResponseEntity.badRequest().body(song);
        }
        return ResponseEntity.ok(song.get());
    }
}

Solution

  • Try to add @Param at ISongRepository and change the return type findByGenre method to List<Song>

    , Also make sure that you retrieve the id or genre from the rest controllers

    @Repository public interface ISongRepository extends JpaRepository<Song, Long>{
    
        @Query("SELECT s FROM Song s WHERE s.genre =:genre")
        List<Song> findByGenre(@Param("genre") String genre); 
    }