I am very new in Java Spring and have a problem where I can not figure out what am I missing.
For the shake of brevity I will make it short:
- I have a controller class with two methods for @GetMapping (get info from a patient in database) and @PostMapping (upload a photo from that patient).
- In both methods, at some point I am calling through "findById" to database and populating a "Patient" model class object.
- All the attributes of this class are retrieved successfully from Database but there is an attribute of this class (getPhoto()) that gets a null value only in the @PostMapping method.
- What am I missing? The code is just the same in both methods.
Thanks very much in advance!!
Controller:
@CrossOrigin(origins="http://localhost:4200", maxAge = 3600)
@RestController
@RequestMapping({"/patients"})
public class PatientController {
@Autowired
IPatientService patientService;
@GetMapping("/{id}")
public ResponseEntity<?> listPatientId(@PathVariable("id") Integer id){
Optional<Patient> patient=null;
Map<String, Object> response=new HashMap<>();
try{
patient=patientService.findById(id);
}catch(DataAccessException e){
response.put("error", e.getMessage().concat(": "+e.getMostSpecificCause().toString()));
new ResponseEntity<Map<String, Object>>(response, HttpStatus.INTERNAL_SERVER_ERROR);
}
System.out.println("Patient with id: "+id+" / "+patient.get().getId()+" which photo is: "+patient.get().getPhoto());
/*Some other code*/
}
@PostMapping("/upload")
public ResponseEntity<?> upload(@RequestParam("archive")MultipartFile archive, @RequestParam("id") Integer id){
Optional<Paciente> paciente = Optional.empty();
Map<String, Object> respuesta= new HashMap<>();
try{
patient=patientService.findById(id);
}catch(DataAccessException e){
response.put("error", e.getMessage().concat(": "+e.getMostSpecificCause().toString()));
new ResponseEntity<Map<String, Object>>(response, HttpStatus.INTERNAL_SERVER_ERROR);
}
System.out.println("Patient with id: "+id+" / "+patient.get().getId()+" which photo is: "+patient.get().getPhoto());
/*Some other code*/
}
}
Patient class:
@Entity
@Table(name = "patients")
public class Patient {
@Id
@Column
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
@Column
private String photo;
(Getters and setters)
}
Repository:
@Repository
public interface PatientRepository extends JpaRepository<Patient, Integer> {
Iterable<Patient> findByNameContainingOrSurnameContaining(String name, String surname);
}
Service (Interface and Implemantation):
public interface IPatientService {
public List<Patient> findAll();
public Optional<Patient> findById(Integer id);
public Iterable<Patient> findByNameContainingOrSurnameContaining(String term);
}
@Service
public class PatientServiceImpl implements IPatientService {
@Autowired
private PatientRepository patientDao;
@Override
@Transactional(readOnly = true)
public List<Patient> findAll() {
return patientDao.findAll();
}
@Override
public Optional<Patient> findById(Integer id) {
return patienteDao.findById(id);
}
public Iterable<Patient> findByNameContainingOrSurnameContaining(String term){
return patientDao.findByNameContainingOrSurnameContaining(term, term);
}
@Override
public Patient save(Patient patient){
return patientDao.save(patient);
}
@Override
public void deleteById(Integer id) {
patientDao.deleteById(id);
}
}
As stated before, "patient.get().getPhoto()" returns in @GetMapping the actual value stored in the database. But in the method annotated with @PostMapping returns null for that value (Although other attributes seem to work just fine).
This was the backend, but in the frontend I am using Angular, where I call this method in component (I am showing just the parts involved in the uploading photo):
patient: Patient;
constructor(private route: ActivatedRoute, private router: Router, private service: ServiceServicee) {
this.paient = new Patient();
}
uploadPhoto() {
this.service.uploadPhoto(this.selectedPhoto,
this.patient.id).subscribe(patient => {
this.patient = patient;
});
}
Service:
constructor(private http:HttpClient, private router:Router) {
this.urlPatients='http://localhost:8080/patients';
}
uploadPhoto(file: File, id):Observable<Patient>{
let formData= new FormData();
formData.append("archive", file);
formData.append("id", id);
return this.http.post(`${this.urlPatients}/upload`, formData).pipe(
map((response:any)=> response.patient as Patient),
catchError(e=>{
console.error(e.error.mensaje);
return throwError(e);
})
);
}
UPDATE: Using Postman and making a POST to http://localhost:8080/patients/upload and sending in the body a jpg file (form-data - "archive") and a id number("id"), I got a success with the inserts and the method it didn't worked previously in the backend (patient.get().getPhoto()) worked perfectly this time. With the same code, so I assume that it is as @BiteBat said and it is a problem of the Frontend and how it is calling the Backend.




@PathVariable("id") Patient patient. However, have you debugged your controller and ensured that the value ofidis actually what you expect? - chrylis -cautiouslyoptimistic-