Web Programming 5: Using Jersey and JPA to create RESTfulWebService

Source: Internet
Author: User
Tags mysql connect
In the previous exercise, I learned how to use Jersey and JAXB to create a RESTful webservice. Now I will upgrade it with the background database, that is, the RESTfulwebservice created through Jersey to modify the background database. Development Environment: EclipseJuno, database MySQL5.5, Jersey1.18, EclipseLink2.4

In the previous exercise, I learned how to use Jersey and JAXB to create a RESTful web service. Now I am upgrading it with the background database, that is, using Jersey to create a RESTful web service for modifying the background database. Development Environment: Eclipse Juno, MySQL 5.5, Jersey 1.18, and EclipseLink 2.4

In the previous exercise, I learned how to use Jersey and JAXB to create a RESTful web service.

Now I am upgrading it with the background database, that is, using Jersey to create a RESTful web service for modifying the background database.

Development Environment:

Eclipse Juno, MySQL 5.5, Jersey 1.18, javasselink 2.4, JAVA 1.6, and Application Server Tomcat 7.

1. Create a Dynamic Web Project called jersey3. Add facet of JPA.

2. Import the Jersey package, the mongoselink package, and the MySQL connect package.

3. Develop database objects and configure JPA.

Data Object Employee class:

package sample;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.Id;import javax.persistence.Table;import javax.xml.bind.annotation.XmlRootElement;@XmlRootElement@Entity@Table(name = "employee")public class Employee {@Id@Column(name = "userId")private Long id;@Column(name = "firstName")private String firstName;@Column(name = "lastName")private String lastName;public long getId() {return id;}public void setId(long id) {this.id = id;}public String getFirstName() {return firstName;}public void setFirstName(String firstName) {this.firstName = firstName;}public String getLastName() {return lastName;}public void setLastName(String lastName) {this.lastName = lastName;}}

Persistence. xml:

 
 
  
   
    org.eclipse.persistence.jpa.PersistenceProvider
   
   
    sample.Employee
   
   
    
    
    
    
   
  
  

4. Configure Jersey and write code to implement RESTful web service.

Create web. xml:

     
       
  
   
RestProjectTest
       
          
   
    
Jersey REST Service
           
   
    
Com. sun. jersey. spi. container. servlet. ServletContainer
           
             
    
     
Com. sun. jersey. config. property. packages
              
    
     
Sample
            
                 
               
    
     
Com. sun. jersey. api. json. POJOMappingFeature
                
    
     
True
            
               
   
    
1
         
        
          
   
    
Jersey REST Service
           
   
    
/*
         
      
            
   
    
Sample. LocalEntityManagerFactory
         
    
 Note that a listener LocalEntityManagerFactory is added to implement the ServletContextListener class, which can be automatically called after the application is started or closed.

You can manage our EntityManager.

package sample;import javax.persistence.EntityManager;import javax.persistence.EntityManagerFactory;import javax.persistence.Persistence;import javax.servlet.ServletContextEvent;import javax.servlet.ServletContextListener;import javax.servlet.annotation.WebListener;@WebListenerpublic class LocalEntityManagerFactory implements ServletContextListener {private static EntityManagerFactory emf;@Overridepublic void contextInitialized(ServletContextEvent event) {emf = Persistence.createEntityManagerFactory("EmployeePU");System.out.println("ServletContextListener started");}@Overridepublic void contextDestroyed(ServletContextEvent event) {emf.close();System.out.println("ServletContextListener destroyed");}public static EntityManager createEntityManager() {if (emf == null) {throw new IllegalStateException("Context is not initialized yet.");}return emf.createEntityManager();}}
After the persistence functions related to JPA are developed, You can implement the RESTful service. Code:
package sample;import java.util.List;import javax.persistence.EntityManager;import javax.persistence.Query;import javax.ws.rs.GET;import javax.ws.rs.Path;import javax.ws.rs.PathParam;import javax.ws.rs.Produces;import javax.ws.rs.core.MediaType;@Path("/employee")public class EmployeeController {@GET@Produces({ MediaType.TEXT_XML })@Path("{id}")public Employee read(@PathParam("id") long id) {long start = System.currentTimeMillis();System.out.println("EmployeeController.read() started");EntityManager em = LocalEntityManagerFactory.createEntityManager();try {return em.find(Employee.class, id);} finally {em.close();System.out.println("Getting data took "+ (System.currentTimeMillis() - start) + "ms.");}}@GET@Produces({ MediaType.TEXT_XML })public List
 
   read() {long start = System.currentTimeMillis();System.out.println("EmployeeController.read() started");EntityManager em = LocalEntityManagerFactory.createEntityManager();try {Query q = em.createQuery("SELECT e FROM Employee e");List
  
    result = q.getResultList();return result;} finally {em.close();System.out.println("Getting data took "+ (System.currentTimeMillis() - start) + "ms.");}}}
  
 

Here we implement two GET interfaces, one returning a single Employee object by ID, and the other returning all Employee objects.

5. Prepare several pieces of test data and insert it into the database table.

6. Test. Here I use the Chrome browser plug-in POSTMAN for testing.

6.1 Test 1, single query

Enter url: http: // localhost: 8080/jersey3/employee/{id}

6.2 Test 2: Query all data

Enter URL: http: // localhost: 8080/jersey3/employee/

Summary:

This example is very simple. After JPA and Jersey are configured, the data CRUD requirements are handed over to the JPA Entity Manager in Jersey's implementation method.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.