如何使用JAX-RS在Java中使用Web Service从数据库插入数据 [英] How to insert data from database with Web Service in java using JAX - RS

查看:109
本文介绍了如何使用JAX-RS在Java中使用Web Service从数据库插入数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是网络服务的新手。请给出如何使用jersey JAX-RS在java中插入和检索数据库的建议?

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

推荐答案

下面是一个示例 JAX-RS 服务实现为会话bean,使用 JPA 进行持久性, JAXB 进行消息传递可能看起来像。

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();
    }

}

客户

以下是其中一个实体的示例。它包含JPA和JAXB注释。

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;

}

更多信息

  • 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

更新


所需的罐子是什么

what are the jars required

您可以将JAX-RS / EJB / JPA / JAXB应用程序部署到任何符合Java EE 6的应用程序服务器,而无需任何其他服务器设置。对客户端进行编程,您可以从Jersey获取JAX-RS API( http://jersey.java.net/),以及EclipseLink的JPA和JAXB API( http://www.eclipse.org/eclipselink/)。

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资源&连接池

您需要在应用程序服务器上配置连接池。以下是在GlassFish上执行此操作的步骤。步骤将根据您使用的应用程序服务器而有所不同。

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. 将JDBC驱动程序(ojdbc14.jar)复制到/ glashfish / lib

  2. 启动管理控制台

  3. 创建连接池:

  1. Copy the JDBC driver (ojdbc14.jar) to /glashfish/lib
  2. Launch the Administration Console
  3. Create a Connection Pool:

  1. 名称= CustomerService

  2. 资源类型='javax.sql.ConnectionPoolDataSource'

  3. 数据库供应商= Oracle(或任何适合您数据库的数据库供应商)

  4. 单击下一步并填写以下其他属性:

  5. 用户(例如CustomerService)

  6. 密码(例如密码)

  7. URL(例如jdbc:oracle:thin:@localhost:1521:XE)

  8. 使用Ping按钮测试你的数据库连接

  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


  • 创建名为CustomerService的JDBC资源

  • Create a JDBC Resource called "CustomerService"


    1. JNDI名称= CustomerService

    2. 池名称= CustomerService(您在上一步中创建的连接池的名称)


  • JPA配置

    然后我们引用我们在上面的JPA实体的 persistence.xml 文件中创建的数据库连接如下:

    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>
    

    这篇关于如何使用JAX-RS在Java中使用Web Service从数据库插入数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆