我正在制作我的第一个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