java - 如何使用 JAX - RS 在 Java 中使用 Web 服务从数据库插入数据

标签 java rest tomcat jersey

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

最佳答案

下面是一个 JAX-RS 服务作为 session bean 实现的示例,使用 JPA 进行持久化,使用 JAXB 进行消息传递可能看起来像.

客户服务

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 注释。

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;

}

了解更多信息


更新

what are the jars required

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

and where the database connections is written

JDBC 资源和连接池

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

  1. 将 JDBC 驱动程序 (ojdbc14.jar) 复制到/glashfish/lib
  2. 启动管理控制台
  3. 创建连接池:
    1. 姓名 = CustomerService
    2. 资源类型 = 'javax.sql.ConnectionPoolDataSource'
    3. 数据库供应商 = Oracle(或任何适合您的数据库的数据库供应商)
    4. 单击“下一步”并填写以下“其他属性”:
    5. 用户(例如 CustomerService)
    6. 密码(例如密码)
    7. URL(例如 jdbc:oracle:thin:@localhost:1521:XE)
    8. 使用“Ping”按钮测试您的数据库连接
  4. 创建一个名为“CustomerService”的 JDBC 资源
    1. JNDI 名称 = CustomerService
    2. Pool Name = CustomerService(您在上一步中创建的连接池的名称)

JPA 配置

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

<?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>

关于java - 如何使用 JAX - RS 在 Java 中使用 Web 服务从数据库插入数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10069901/

相关文章:

java - 奇怪的 Atomikos 异常 - init() : Log already in use? 中的错误

java - 如何从 Retrofit onResponse() 更新 Activity/Fragment UI?

java - JSONObject 到 Java bean 类不起作用

json - 使用 Google 自定义搜索 API 获取 Google 图片中图片的 URL?

c# - Web API 2 REST 服务高级数据过滤

java - 为什么我的 jasperserver 不允许我将图像(或任何 "file")上传到存储库?

java - 如何删除tomcat中加载的Jar文件?

java - 如何启动在其他Android 项目中定义的 Activity ?

java - 无法为客户端形成正确的 JSON 响应

java - 如何在 java 方法 atZone(Zone_ID) 中定义 IST 区域 ID;