Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
448 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...