Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package cimitero.rest; import cimitero.dto.ItemWrapper; import cimitero.dto.ResponseDto; import cimitero.entities.TPerson; import cimitero.persistence.HibernateUtil; import java.util.ArrayList; import java.util.List; import javax.ejb.Stateless; import javax.ws.rs.Consumes; import javax.ws.rs.Path; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.DELETE; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.hibernate.Session; import org.jboss.logging.Logger; /** * REST Web Service * * @author Markus */ @Stateless @Path("/person") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) public class PersonRESTService { Logger log = Logger.getLogger(PersonRESTService.class); public PersonRESTService() { } // get all person entries @GET public ResponseDto getAllPersons() { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); List<TPerson> results = session.createCriteria(TPerson.class).list(); ResponseDto response = new ResponseDto(true); if (results.isEmpty()) { response.setOk(false); response.addError(1, "no entries found"); } else { response.setItems(new ItemWrapper<TPerson>(results)); } session.getTransaction().commit(); return response; } // get person by id @GET @Path("{id}") public ResponseDto getPersonById(@PathParam("id") Integer id) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); TPerson result = (TPerson) session.get(TPerson.class, id); ResponseDto response = new ResponseDto(true); if (result == null) { response.setOk(false); response.addError(1, "person with id " + id + " not found"); } else { List<TPerson> results = new ArrayList<TPerson>(); results.add(result); response.setItems(new ItemWrapper(results)); } session.getTransaction().commit(); return response; } // save or update person @POST public ResponseDto updatePerson(TPerson person) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); if (person.getPersonId() == -1) person.setPersonId(null); session.saveOrUpdate(person); ResponseDto response = new ResponseDto(true); session.getTransaction().commit(); return response; } // delete person @DELETE @Path("{id}") public ResponseDto removePerson(@PathParam("id") Integer id) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); TPerson result = (TPerson) session.get(TPerson.class, id); session.delete(result); ResponseDto response = new ResponseDto(true); session.getTransaction().commit(); return response; } }