search
HomeDatabaseMysql TutorialWeb编程学习五:使用Jersey和JPA来创建RESTfulWebService

在上一个练习学习了如何使用Jersey,以及JAXB来创建RESTful的web service。 现在我来结合后台数据库对其做升级,也就是通过Jersey创建用来修改后台数据库的RESTful web service。 开发环境: Eclipse Juno, 数据库MySQL 5.5, Jersey 1.18,EclipseLink 2.4

在上一个练习学习了如何使用Jersey,以及JAXB来创建RESTful的web service。

现在我来结合后台数据库对其做升级,也就是通过Jersey创建用来修改后台数据库的RESTful web service。

开发环境:

Eclipse Juno, 数据库MySQL 5.5, Jersey 1.18,EclipseLink 2.4, JAVA 1.6, 应用服务器Tomcat 7。

1.创建一个叫做jersey3的Dynamic Web Project。添加JPA的facet。

2.导入Jersey包,导入EclipseLink包,导入MySQL的connect包。

3.开发数据库对象,配置JPA。

数据对象Employee类:

package sample;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
@Entity
@Table(name = "employee")
public class Employee {
	@Id
	@Column(name = "userId")
	private Long id;
	@Column(name = "firstName")
	private String firstName;
	@Column(name = "lastName")
	private String lastName;

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
}

persistence.xml:

 

\

 

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.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_2_0.xsd">
	<persistence-unit name="EmployeePU" transaction-type="RESOURCE_LOCAL">
		<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
		<class>sample.Employee</class>
		<properties>
			<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:8889/test" />
			<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
			<property name="javax.persistence.jdbc.user" value="root" />
			<property name="javax.persistence.jdbc.password" value="root" />
		</properties>
	</persistence-unit>
</persistence> 

4.配置Jersey,编写代码来实现RESTful web service。

创建web.xml:

<?xml version="1.0" encoding="UTF-8"?>    
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">    
  <display-name>RestProjectTest</display-name>    
 <servlet>    
    <servlet-name>Jersey REST Service</servlet-name>    
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>    
    <init-param>    
      <param-name>com.sun.jersey.config.property.packages</param-name>    
      <param-value>sample</param-value>    
    </init-param>    
          <init-param>    
        <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>    
        <param-value>true</param-value>    
    </init-param>        
    <load-on-startup>1</load-on-startup>    
  </servlet>    
  <servlet-mapping>    
    <servlet-name>Jersey REST Service</servlet-name>    
    <url-pattern>/*</url-pattern>    
  </servlet-mapping>    
<listener>  
        <listener-class>sample.LocalEntityManagerFactory</listener-class>  
    </listener></span>  
</web-app>   

注意添加了一个监听器LocalEntityManagerFactory,实现了ServletContextListener类,它可以在应用启动和关闭的时候后自动调用。

可以来管理我们的EntityManager。

package sample;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class LocalEntityManagerFactory implements ServletContextListener {
	private static EntityManagerFactory emf;

	@Override
	public void contextInitialized(ServletContextEvent event) {
		emf = Persistence.createEntityManagerFactory("EmployeePU");
		
		System.out.println("ServletContextListener started");
	}

	@Override
	public void contextDestroyed(ServletContextEvent event) {
		emf.close();
		System.out.println("ServletContextListener destroyed");
	}

	public static EntityManager createEntityManager() {
		if (emf == null) {
			throw new IllegalStateException("Context is not initialized yet.");
		}
		return emf.createEntityManager();
	}
}
开发好JPA相关的持久化功能后,就可以来实现RESTful service了,代码:
package sample;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/employee")
public class EmployeeController {
	@GET
	@Produces({ MediaType.TEXT_XML })
	@Path("{id}")
	public Employee read(@PathParam("id") long id) {
		long start = System.currentTimeMillis();
		System.out.println("EmployeeController.read() started");
		EntityManager em = LocalEntityManagerFactory.createEntityManager();
		try {
			return em.find(Employee.class, id);
		} finally {
			em.close();
			System.out.println("Getting data took "
					+ (System.currentTimeMillis() - start) + "ms.");
		}
	}

	@GET
	@Produces({ MediaType.TEXT_XML })
	public List<Employee> read() {
		long start = System.currentTimeMillis();
		System.out.println("EmployeeController.read() started");
		EntityManager em = LocalEntityManagerFactory.createEntityManager();
		try {
			Query q = em.createQuery("SELECT e FROM Employee e");
			List<Employee> result = q.getResultList();
			return result;
		} finally {
			em.close();
			System.out.println("Getting data took "
					+ (System.currentTimeMillis() - start) + "ms.");
		}
	}

}

这里实现了两个GET接口,一个按照ID返回单个Employee对象,另一个返回全部Employee对象。

5.准备几条测试数据,插入到数据库表中。

\

6.测试,这里我用的Chrome浏览器插件的POSTMAN来测试。

6.1测试1,单个查询

输入url: http://localhost:8080/jersey3/employee/{id}

\

6.2测试2,查询全部数据

输入URL: http://localhost:8080/jersey3/employee/\

小结:

这个例子很简单,配置好JPA和Jersey后,主要就是在Jersey的实现方法中把数据的CRUD需求交给JPA的Entity Manager来完成就可以了。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does MySQL differ from SQLite?How does MySQL differ from SQLite?Apr 24, 2025 am 12:12 AM

The main difference between MySQL and SQLite is the design concept and usage scenarios: 1. MySQL is suitable for large applications and enterprise-level solutions, supporting high performance and high concurrency; 2. SQLite is suitable for mobile applications and desktop software, lightweight and easy to embed.

What are indexes in MySQL, and how do they improve performance?What are indexes in MySQL, and how do they improve performance?Apr 24, 2025 am 12:09 AM

Indexes in MySQL are an ordered structure of one or more columns in a database table, used to speed up data retrieval. 1) Indexes improve query speed by reducing the amount of scanned data. 2) B-Tree index uses a balanced tree structure, which is suitable for range query and sorting. 3) Use CREATEINDEX statements to create indexes, such as CREATEINDEXidx_customer_idONorders(customer_id). 4) Composite indexes can optimize multi-column queries, such as CREATEINDEXidx_customer_orderONorders(customer_id,order_date). 5) Use EXPLAIN to analyze query plans and avoid

Explain how to use transactions in MySQL to ensure data consistency.Explain how to use transactions in MySQL to ensure data consistency.Apr 24, 2025 am 12:09 AM

Using transactions in MySQL ensures data consistency. 1) Start the transaction through STARTTRANSACTION, and then execute SQL operations and submit it with COMMIT or ROLLBACK. 2) Use SAVEPOINT to set a save point to allow partial rollback. 3) Performance optimization suggestions include shortening transaction time, avoiding large-scale queries and using isolation levels reasonably.

In what scenarios might you choose PostgreSQL over MySQL?In what scenarios might you choose PostgreSQL over MySQL?Apr 24, 2025 am 12:07 AM

Scenarios where PostgreSQL is chosen instead of MySQL include: 1) complex queries and advanced SQL functions, 2) strict data integrity and ACID compliance, 3) advanced spatial functions are required, and 4) high performance is required when processing large data sets. PostgreSQL performs well in these aspects and is suitable for projects that require complex data processing and high data integrity.

How can you secure a MySQL database?How can you secure a MySQL database?Apr 24, 2025 am 12:04 AM

The security of MySQL database can be achieved through the following measures: 1. User permission management: Strictly control access rights through CREATEUSER and GRANT commands. 2. Encrypted transmission: Configure SSL/TLS to ensure data transmission security. 3. Database backup and recovery: Use mysqldump or mysqlpump to regularly backup data. 4. Advanced security policy: Use a firewall to restrict access and enable audit logging operations. 5. Performance optimization and best practices: Take into account both safety and performance through indexing and query optimization and regular maintenance.

What are some tools you can use to monitor MySQL performance?What are some tools you can use to monitor MySQL performance?Apr 23, 2025 am 12:21 AM

How to effectively monitor MySQL performance? Use tools such as mysqladmin, SHOWGLOBALSTATUS, PerconaMonitoring and Management (PMM), and MySQL EnterpriseMonitor. 1. Use mysqladmin to view the number of connections. 2. Use SHOWGLOBALSTATUS to view the query number. 3.PMM provides detailed performance data and graphical interface. 4.MySQLEnterpriseMonitor provides rich monitoring functions and alarm mechanisms.

How does MySQL differ from SQL Server?How does MySQL differ from SQL Server?Apr 23, 2025 am 12:20 AM

The difference between MySQL and SQLServer is: 1) MySQL is open source and suitable for web and embedded systems, 2) SQLServer is a commercial product of Microsoft and is suitable for enterprise-level applications. There are significant differences between the two in storage engine, performance optimization and application scenarios. When choosing, you need to consider project size and future scalability.

In what scenarios might you choose SQL Server over MySQL?In what scenarios might you choose SQL Server over MySQL?Apr 23, 2025 am 12:20 AM

In enterprise-level application scenarios that require high availability, advanced security and good integration, SQLServer should be chosen instead of MySQL. 1) SQLServer provides enterprise-level features such as high availability and advanced security. 2) It is closely integrated with Microsoft ecosystems such as VisualStudio and PowerBI. 3) SQLServer performs excellent in performance optimization and supports memory-optimized tables and column storage indexes.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.