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

后端 未结 2 1622
时光取名叫无心
时光取名叫无心 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<Customer> 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<PhoneNumber> 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:

    <?xml version="1.0" encoding="UTF-8"?>
    <persistence version="1.0"
        xmlns="http://java.sun.com/xml/ns/persistence"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
        <persistence-unit name="CustomerService" transaction-type="JTA">
            <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
            <jta-data-source>CustomerService</jta-data-source>
            <class>org.example.Customer</class>
            <class>org.example.Address</class>
            <class>org.example.PhoneNumber</class>
            <properties>
                <property name="eclipselink.target-database" value="Oracle" />
                <property name="eclipselink.logging.level" value="FINEST" />
                <property name="eclipselink.logging.level.ejb_or_metadata" value="WARNING" />
                <property name="eclipselink.logging.timestamp" value="false"/>
                <property name="eclipselink.logging.thread" value="false"/>
                <property name="eclipselink.logging.session" value="false"/>
                <property name="eclipselink.logging.exceptions" value="false"/> 
                <property name="eclipselink.target-server" value="SunAS9"/> 
            </properties>
        </persistence-unit>
    </persistence>
    
    0 讨论(0)
  • 2020-12-13 08:28

    Have a look at this link, there is a video tutorial that explains one way how it can be done.

    So the video is explaining how a web service retrieves some value to tell the client that the given credentials match against some data in a database.

    This is how the method that handle the client request looks like:

    @POST
        @Produces(MediaType.TEXT_PLAIN)
        @Path("/login")
        public Response login(@FormParam("email") String email, @FormParam("password") String password) {
    
            Response.ResponseBuilder responseBuilder = null;
            
            boolean result = entityFacade.doLogin(email, password);
            if (result) {
                 responseBuilder = Response.ok("Success");//Login good!
            }
            else {            
                responseBuilder = Response.ok("Wrong credentials!");//Login bad!
            }
    
            return responseBuilder.build();
        }
    

    This Web service transfers the credentials to the business layer where an EJB will perform a select operation in the database:

    @Stateless
    public class EntityFacade implements EntityFacadeLocal {
    
        @Resource
        private UserTransaction ut;
        private CredentialJpaController controller;
    
        @PostConstruct
        public void init() {        
            controller = new CredentialJpaController(ut, Persistence.createEntityManagerFactory("ROLEProject-ejbPU"));
        }
    
    
        public boolean doLogin(String email, String password){        
            return controller.loginWithParameters(email,password);
        }
    }
    

    The EJB relies in a service class that will do the task of interact with the database

    public class CredentialJpaController implements Serializable {
    
        public CredentialJpaController(UserTransaction utx, EntityManagerFactory emf) {
            this.utx = utx;
            this.emf = emf;
        }
        private UserTransaction utx = null;
        private EntityManagerFactory emf = null;
    
        public EntityManager getEntityManager() {
            return emf.createEntityManager();
        }
        public boolean loginWithParameters(String email, String password) {
            boolean result = false;
            EntityManager em = getEntityManager();
            Long l = (Long) em.createNamedQuery("loginquery").setParameter("emailParam", email).setParameter("passwordParam", password).getSingleResult();
            if (l == 1) {
                result = true;
            }
            return result;
        }
    }
    

    Finally to be able to interact with the DB, the data must be represented as a JPA entity. Also to be able to marshal the selected row back to the client as whatever MediaType is desired, the entity must contain some JaxB annotations:

    @XmlRootElement
    @Entity
    @Table(name = "CREDENTIALS")
    @NamedQuery(name="loginquery", query="SELECT COUNT(c) FROM Credential c WHERE c.email = :emailParam AND c.password = :passwordParam")
    public class Credential implements Serializable {
    
        @Id
        private String email;
        @Column(nullable = false)
        private String password;
    
        @XmlElement
        public String getEmail() {
            return email;
        }
    
        public void setEmail(String email) {
            this.email = email;
        }
    
         @XmlElement
        public String getPassword() {
            return password;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    }
    

    Here is some sample client code so you can see one of the ways how the web-service can be called:

    <html xmlns="http://www.w3.org/1999/xhtml">
        <head>
            <title>TODO supply a title</title>
        </head>
        <body>
            <div>TODO write content</div>
            <form action="http://localhost:8080/ROLEProject-war/role/login" method="POST">
                Email <input name="email"/>
                Password <input type="password" name="password"/>
                <input type="submit"/>
            </form>
        </body>
    </html>
    

    I hope this helps to give you an idea.

    To do insert data the process is almost the same, just use the method persist() instead of find() from the entity manager.

    0 讨论(0)
提交回复
热议问题