Skip to main content

Notice: this Wiki will be going read only early in 2024 and edits will no longer be possible. Please see: https://gitlab.eclipse.org/eclipsefdn/helpdesk/-/wikis/Wiki-shutdown-plan for the plan.

Jump to: navigation, search

Difference between revisions of "EclipseLink/DesignDocs/326663"

(Unary Key)
(Unary Key)
Line 89: Line 89:
 
</source>
 
</source>
  
 +
URI to find the instance of Customer with id == 1:
 
*http://www.example.com/customer-app/rest/customers/1
 
*http://www.example.com/customer-app/rest/customers/1
  

Revision as of 09:53, 1 October 2010

Design Specification: JPA RESTful Service

ER 326663

Document History

Date Author Version Description & Notes
2010/09/30 Blaise Doughan Initial Version

Project overview

Provide an easy means for users to expose their JPA entities through a RESTful service.

Goals:

  • Provide a means for users to implement a standards (JAX-RS/JAXB/JPA) based RESTful service with minimal code.

Concepts

The following example demonstrates how JAXB and JPA can be used to implement a RESTful (JAX-RS) web service:

Resources & URIs

Each resource needs to be locatable with a URI.

Entity - Single Key

 

Entity - Composite Key

 

Named Query

 

Requirements

  • Expose JPA EntityManager as RESTful (JAX-RS) service
  • Execute CRUD operations
  • Execute named queries
  • Accept/Return both XML and JSON mime types
  • Convert JPA exceptions into appropriate HTTP response codes

Design Constraints

  • JAX-RS operates on the HTTP protocol, we will be limited by the constraints of this protocol.
    • URI parameters are limited to simple types
    • Error conditions are limited to response codes
    • Operations either produce data or consume data, not both

Design / Functionality

URI Representation

Data in a RESTful service is referenced through URIs.

The common parts of the URI are:

Unary Key

If the JPA entity has a single part primary key then in the corresponding URI the primary key will be represented as a path parameter. This is a common RESTful operation.

@Entity
public class Customer implements Serializable {
 
    @Id
    private long id;
 
}

URI to find the instance of Customer with id == 1:

Composite Keys

A different mechanism needs be be employed when locating a resource with composite keys. The URI will leverage the property names from the JPA key class. The advantage of using matrix paremters is that they may be cached.

Option #1 - Matrix Parameters

Option #2 - Query Parameters

Named Queries

A named query call needs to be mapped to a URI. Below is an example named query:

@NamedQuery(name = "findCustomerByName",
            query = "SELECT c " +
                    "FROM Customer c " +
                    "WHERE c.firstName = :firstName AND " +
                    "      c.lastName = :lastName")

Get Single Result:

Get Result List:

URI components:

  • findCustomersByName - this corresponds to the name of the named query
  • singleResult or resultList - this portion indicates whether one or many results are returned
  • ?firstName=Jane&lastName=Doe - these are the query parameters, the name of the parameter must match exactly the parameter name in the named query.

REST (CRUD) Operations

POST - Create Operation

@POST
@Consumes(MediaType.APPLICATION_XML)
public void create(Customer customer) {
 entityManager.persist(customer);
}

Successful Responses

  • 200 OK

Error Responses:

GET - Read Operation

Get is a read-only operation. It is used to query resources.

@GET
@Produces(MediaType.APPLICATION_XML)
@Path("{id}")
public Customer read(@PathParam("id") long id) {
 return entityManager.find(Customer.class, id);
}

Successful Responses

  • 200 OK - If a result is returned
  • 204 No Content - If no results are returned

Error Responses:

PUT - Update Operation

The put operation updates the underlying resource. When using put the client knows the identity of the resource being updated.

@PUT
@Consumes(MediaType.APPLICATION_XML)
public void update(Customer customer) {
 entityManager.merge(customer);
}

Successful Responses

  • 200 OK

Error Responses:

  • 409 Conflict - Locking related exception

DELETE - Delete Operation

The delete operation is used to remove resources. It is not an error to remove a non-existent resource.

@DELETE
@Path("{id}")
public void delete(@PathParam("id") long id) {
 Customer customer = read(id);
 if (null != customer) {
 entityManager.remove(customer);
 }
}

Successful Responses

  • 200 OK

Error Responses:

Testing

API

The user would implement their JPA based JAX-RS service as follows. They would extend JPASingleKeyResource or JPACompositeKeyResource depending upon their key type.

import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;
import javax.ws.rs.Path;
 
import org.eclipse.persistence.rest.JPASingleKeyResource;
 
@Stateless
@LocalBean
@Path("/customers")
public class CustomerService extends JPASingleKeyResource<Customer, Long> {
 
    @PersistenceContext(unitName="CustomerService", type=PersistenceContextType.TRANSACTION)
    EntityManager entityManager;
 
    public CustomerService() {
        super(Customer.class);
    }
 
    @Override
    protected EntityManager entityManager() {
        return entityManager;
    }
 
}

GUI

Config files

This feature does not require the creation of any new configuration files. However the user will be responsible for providing the required JAX-RS, JPA, and JAXB config files.

JAX-RS

  • The user will need to create the JAX-RS deployment artifacts appropriate to their deployment platform.

JPA

  • The user will need to create the necessary artifacts for JPA

JAXB

  • The user will need to create the necessary artifacts for JAXB
    • jaxb.properties file to specify JAXB implementation
    • eclipselink-oxm.xml as an alternate metadata representation

Documentation

Open Issues

This section lists the open issues that are still pending that must be decided prior to fully implementing this project's requirements.

Issue # Owner Description / Notes
1 Blaise Doughan When to use matrix and/or query parameters? Will consult with Paul Sandoz to resolve this issue.

Decisions

This section lists decisions made. These are intended to document the resolution of open issues or constraints added to the project that are important.

Issue # Description / Notes Decision

Future Considerations

During the research for this project the following items were identified as out of scope but are captured here as potential future enhancements. If agreed upon during the review process these should be logged in the bug system.

Back to the top