我正在製作我的第一個REST風格的Web服務(使用MySQL)。但我不知道如何通過id從表中刪除記錄。在REST風格的Web服務中添加刪除方法
這是我迄今所做的:通過ID
搜索一個人,並以XML格式返回結果(ID,姓名和年齡):
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
按ID搜索某個人,並以JSON格式返回結果(id,姓名和年齡):
@GET @Path("/getPersonByIdJSON/{id}") @Produces(MediaType.APPLICATION_JSON) public Person getPersonById(@PathParam("id")int id){ return personDao.getPersonById(id); }
輸出的所有人員和JSON格式返回結果(ID,姓名和年齡):
//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\"}"; } }
編輯一個人在數據庫:
// the method returns list of all persons @GET @Path("/getAllPersonsInXML") @Produces(MediaType.APPLICATION_XML) public List<Person> getAllPersonsInXML(){ return personDao.getAllPersons(); }
在數據庫中插入一個人:
//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\"}"; } }
謝謝,我使deleteById方法,但他不工作。下一個答案中的代碼 – Lev 2015-04-02 09:46:50