I need to return a service info by id. I've tried different variations of writing my code but they all lead to java not seeing the value by its id.
Service Model:
@Entity
@Getter
@Setter
public class Service {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private BigDecimal price;
}
Service:
public class ServiceService {
@Autowired
private ServiceRepo serviceRepo;
public Service getById(Long id) {
return serviceRepo.findById(id).get();
}
}
Repository:
public interface ServiceRepo extends JpaRepository<Service, Long>, JpaSpecificationExecutor<Service> {
Optional<Service> findById(Long id);
}
And conroller:
@Controller
public class AllServices {
@Autowired
private ServiceRepo serviceRepo;
@GetMapping("/services")
public String allServices(Model model){
List<Service> services = serviceRepo.findAll();
model.addAttribute("services", services);
return "services";
}
@Autowired
private ServiceService serviceService;
@GetMapping("/services/{id}")
public ResponseEntity<Service> getServiceById(@RequestParam(value = "id", required = false) Long id){
try{
Service service = serviceService.getById(id);
return new ResponseEntity<>(service, HttpStatus.OK);
}catch(NoSuchElementException e){
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
}
When it comes to all services, it returns all values, but here it doesn't see them.
These answers and many others didn't help:
JPA Repository.findById() returns null but the value is exist on db