Issue
How can I check the DB if a record already exists for a given case using Spring JPA query using one params. If it exists it does an update or else it inserts as a new record. I have tried a simple implementation, but I end up with a 500 server error no other error is logged.
Resolved [java.lang.NullPointerException] Completed 500 INTERNAL_SERVER_ERROR
This is what I have tried so far My Controller
@RequestMapping(path="/updatedm",method = RequestMethod.POST)
public Boolean updateDMStatus(@RequestParam("country") String country,
@RequestParam("Id") String pId,
@RequestParam("case") String case,
@RequestParam("status") String status,
@RequestParam("updatedBy") String updatedBy){
Boolean createDm = eaDataStoreService.updateDM(country,Id,case,status,updatedBy);
return createDm;
}
My repository
public interface DMValidatedRepository extends CrudRepository<DMValidated, String> {
DMValidated findByCase(@Param("case") String case);
}
My Service
public boolean updateDM(String country, String Id, String case, String status,String updatedBy) {
DMValidated document = dmValidated.findByCase(case);
if(document != null){
document.setStatus(status);
document.setUpdatedBy(updatedBy);
dmValidated.save(document);
}else{
document.getId();
document.getCase();
document.getCountry();
document.getStatus();
document.getUpdatedBy();
dmValidated.save(document);
}
return true;
}
My Model
@Data
@ToString
@Entity
@Table(name = "DMStatus")
public class DMValidated{
@Id
@GeneratedValue
private String id;
@Column(name = "country")
private String country;
@Column(name = "Id")
private String Id;
@Column(name = "Case")
private String case;
@Column(name = "status")
private String status;
@Column(name = "updatedBy")
private String updatedBy;
public DMValidated( String country, String Id,
String case, String status, String updatedBy){
this.country = country;
this.Id=Id;
this.case = case;
this.status =status;
this.updatedBy = updatedBy;
}
Am not sure if this is the right way of doing this, have tried to research but I have not found something concreate. How can I achieve this?
Solution
It's not difficult you have just forgotten the code to create properly the object when it is new and needs to be inserted
if(document != null){
document.setStatus(status);
document.setUpdatedBy(updatedBy);
}else{
document = new DMValidated();
document.setId(Id);
document.setCase(case);
document.setCountry(country);
document.setStatus(status);
document.setUpdatedBy(updatedBy);
}
dmValidated.save(document);
The error that occurred previously in your code is the following
}else{
document.getId();
...
}
In this else you get only when document == null
, so when you invoke document.getId()
a null pointer exception is thrown, and then 500 error occurs.
Answered By - Panagiotis Bougioukos