I am making my first RESTful web service (using MySQL). But I don't know how to remove records from a table by id.
This is what I have done so far:
Search for a person by id and return the result(id, full name and age) in XML format:
private PersonDao personDao = new PersonDao();
//method which return a single person in xml
@GET
@Path("/getPersonByIdXML/{id}")
@Produces(MediaType.APPLICATION_XML)
public Person getPersonByIdXML(@PathParam("id")int id){
return personDao.getPersonById(id);
}
// return JSON response
Search for a person by id and return the result(id, full name and age) in JSON format:
@GET
@Path("/getPersonByIdJSON/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Person getPersonById(@PathParam("id")int id){
return personDao.getPersonById(id);
}
Output all persons and return the result(id, full name and age) in JSON format:
// the method returns list of all persons
@GET
@Path("/getAllPersonsInXML")
@Produces(MediaType.APPLICATION_XML)
public List<Person> getAllPersonsInXML(){
return personDao.getAllPersons();
}
Insert a person in the database:
//insert
@GET
@Path("/insertPerson/{fullName}/{age}")
@Produces(MediaType.APPLICATION_JSON)
public String saveNewPerson(@PathParam("fullName") String fullName, @PathParam("age") int age) {
Person person = new Person();
person.setFullName(fullName);
person.setAge(age);
if (!personDao.savePerson(person)) {
return "{\"status\":\"ok\"} id="+person.getId();
}
else {
return "{\"status\":\"not ok\"}";
}
}
Edit a person in the database:
//update
@GET
@Path("/insertPerson/{id}/{fullName}/{age}")
@Produces(MediaType.APPLICATION_JSON)
public String updatePerson(@PathParam("id") int id, @PathParam("fullName") String fullName, @PathParam("age") int age) {
Person person = new Person();
person.setId(id);
person.setFullName(fullName);
person.setAge(age);
if (!personDao.savePerson(person)) {
return "{\"status\":\"ok\"}";
}
else {
return "{\"status\":\"not ok\"}";
}
}
If you want a DELETE resource:
@DELETE
@Path("/{id}")
public void deleteById(@PathParam("id")int id){
personDao.deleteById(id);
}
As long as you have the deleteById method constructed then Thanks it!
Suggestions:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With