How to insert data from database with Web Service in java using JAX - RS

后端 未结 2 1626
时光取名叫无心
时光取名叫无心 2020-12-13 08:01

I am new to web services. Please give suggestions how to insert and retrieve data from database using jersey JAX - RS in java?

2条回答
  •  失恋的感觉
    2020-12-13 08:12

    Below is an example of a JAX-RS service implemented as a session bean using JPA for persistence and JAXB for messaging might look like.

    CustomerService

    package org.example;
    
    import java.util.List;
    
    import javax.ejb.*;
    import javax.persistence.*;
    import javax.ws.rs.*;
    import javax.ws.rs.core.MediaType;
    
    @Stateless
    @LocalBean
    @Path("/customers")
    public class CustomerService {
    
        @PersistenceContext(unitName="CustomerService",
                            type=PersistenceContextType.TRANSACTION)
        EntityManager entityManager;
    
        @POST
        @Consumes(MediaType.APPLICATION_XML)
        public void create(Customer customer) {
            entityManager.persist(customer);
        }
    
        @GET
        @Produces(MediaType.APPLICATION_XML)
        @Path("{id}")
        public Customer read(@PathParam("id") long id) {
            return entityManager.find(Customer.class, id);
        }
    
        @PUT
        @Consumes(MediaType.APPLICATION_XML)
        public void update(Customer customer) {
            entityManager.merge(customer);
        }
    
        @DELETE
        @Path("{id}")
        public void delete(@PathParam("id") long id) {
            Customer customer = read(id);
            if(null != customer) {
                entityManager.remove(customer);
            }
        }
    
        @GET
        @Produces(MediaType.APPLICATION_XML)
        @Path("findCustomersByCity/{city}")
        public List findCustomersByCity(@PathParam("city") String city) {
            Query query = entityManager.createNamedQuery("findCustomersByCity");
            query.setParameter("city", city);
            return query.getResultList();
        }
    
    }
    

    Customer

    Below is an example of one of the entities. It contains both JPA and JAXB annotations.

    package org.example;
    
    import java.io.Serializable;
    import javax.persistence.*;
    import javax.xml.bind.annotation.XmlRootElement;
    
    import java.util.Set;
    
    @Entity
    @NamedQuery(name = "findCustomersByCity",
                query = "SELECT c " +
                        "FROM Customer c " +
                        "WHERE c.address.city = :city")
    @XmlRootElement
    public class Customer implements Serializable {
        private static final long serialVersionUID = 1L;
    
        @Id
        private long id;
    
        @Column(name="FIRST_NAME")
        private String firstName;
    
        @Column(name="LAST_NAME")
        private String lastName;
    
        @OneToOne(mappedBy="customer", cascade={CascadeType.ALL})
        private Address address;
    
        @OneToMany(mappedBy="customer", cascade={CascadeType.ALL})
        private Set phoneNumbers;
    
    }
    

    For More Information

    • Part 1 - Data Model
    • Part 2 - JPA
    • Part 3 - JAXB (using MOXy)
    • Part 4 - RESTful Service (using an EJB session bean)
    • Part 5 - The client

    UPDATE

    what are the jars required

    You can deploy a JAX-RS/EJB/JPA/JAXB application to any Java EE 6 compliant application server without requiring any additional server set up. Programming the client you can get the JAX-RS APIs from the Jersey (http://jersey.java.net/), and the JPA and JAXB APIs from EclipseLink (http://www.eclipse.org/eclipselink/).

    and where the database connections is written

    JDBC Resource & Connection Pool

    You need to configure a connection pool on your application server. Below are the steps to do this on GlassFish. The steps will vary depending on the application server you are using.

    1. Copy the JDBC driver (ojdbc14.jar) to /glashfish/lib
    2. Launch the Administration Console
    3. Create a Connection Pool:
      1. Name = CustomerService
      2. Resource Type = 'javax.sql.ConnectionPoolDataSource'
      3. Database Vendor = Oracle (or whatever database vendor is appropriate to your database)
      4. Click Next and fill in the following "Additional Properties":
      5. User (e.g. CustomerService)
      6. Password (e.g. password)
      7. URL (e.g. jdbc:oracle:thin:@localhost:1521:XE)
      8. Use the "Ping" button to test your database connection
    4. Create a JDBC Resource called "CustomerService"
      1. JNDI Name = CustomerService
      2. Pool Name = CustomerService (name of the connection pool you created in the previous step)

    JPA Configuration

    Then we reference the database connection we created above in the persistence.xml file for our JPA entities as follows:

    
    
        
            org.eclipse.persistence.jpa.PersistenceProvider
            CustomerService
            org.example.Customer
            org.example.Address
            org.example.PhoneNumber
            
                
                
                
                
                
                
                 
                 
            
        
    
    

提交回复
热议问题