package com.trifulcas.SpringBootBiblioteca.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import com.trifulcas.SpringBootBiblioteca.model.Libro;
public interface LibroRepository extends JpaRepository<Libro, Integer> {
List<Libro> findByPaginasBetweenOrderByPaginasAsc(Integer a, Integer b);
}
package com.trifulcas.SpringBootBiblioteca.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import com.trifulcas.SpringBootBiblioteca.model.Genero;
public interface GeneroRepository extends JpaRepository<Genero, Integer> {
// Dentro del repositorio podemos crear consultas de una manera 'mágica'
List<Genero> findByNombreContaining(String nombre);
}
En el controlador:
@GetMapping("")
public List<Genero> getAll(@RequestParam(required=false) String nombre) {
try {
if (nombre==null) {
return generoRepository.findAll();
}else {
return generoRepository.findByNombreContaining(nombre);
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
return null;
}
}
Url:
http://localhost:8080/libro?nombre=fi
@GetMapping("")
public List<Libro> getAll(@RequestParam(required=false) Integer min,@RequestParam(required=false) Integer max) {
try {
if (min==null || max==null) {
return libroRepository.findAll();
}else {
return libroRepository.findByPaginasBetweenOrderByPaginasAsc(min, max);
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
return null;
}
}
Otro ejemplo, buscar los libros de un autor determinado
En el repository:
List<Libro> findByAutoresIdautor(Integer id);
En el controlador, creo un endpoint nuevo
@GetMapping("/autor/{id}")
public List<Libro> getByIdAutor(@PathVariable int id) {
System.out.println(id);
try {
return libroRepository.findByAutoresIdautor(id);
} catch (Exception ex) {
System.out.println(ex.getMessage());
return null;
}
}