April 12, 2013

Introducing EclipseLink JPA-RS

In a previous series of posts I covered how to create a JAX-RS service that leveraged JPA for the persistence layer.  EclipseLink contains a component called JPA-RS that can be used to easily and automatically expose a persistence unit as RESTful service (that supports XML and JSON messages).  MOXy provides the XML and JSON-binding for JPA-RS and things like bidirectional mappings are automatically mapped for you.  In another post I cover how MOXy can be used to customize the messages shown in this example.

I will use the JPA model that I created in the posts below:

Packaging/Deployment 

Using JPA-RS is a simple matter of packaging.  We will create a WAR that contains our JPA model in a JAR, the JPA-RS JAR, and a simple session bean to initialize our JPA model.  For this example I am using a promoted build of GlassFish 4.0 that contains EclipseLink 2.5.

CustomerJPARS.war
  • WEB-INF
    • classes
      • org
        • example
          • ejb
            • PersistenceWeaverBean.class
    • lib
      • CustomerJPA.jar
      • org.eclipse.persistence.jpars_2.5.0.qualifier.jar
  • META-INF
    • MANIFEST.MF 

PersistenceWeaverBean 

JPA-RS requires that the JPA entities have been initialized.  We'll create a simple session bean to accomplish this.

package org.example.ejb;

import javax.ejb.*;
import javax.persistence.*;

@Startup
@Singleton
@LocalBean
public class PersistenceWeaverBean {

    @SuppressWarnings("unused")
    @PersistenceUnit(unitName = "CustomerService")
    private EntityManagerFactory emf;

}

CustomerJPA.jar

This JAR contains the JPA model that we defined in the following post:  

org.eclipse.persistence.jpars_2.5.0.qualifier.jar

This is the JPA-RS JAR that comes from the EclipseLink install:

<ECLIPSELINK_HOME>/jlib/jpa/org.eclipse.persistence.jpars_2.5.0.qualifier.jar


What Can I Do with My Service? (Service Metadata)

As soon as we have deployed the WAR our service is active.  We can perform a GET to see the metadata for our service.

GET (application/xml or application/json)

The URI to get the metadata for a service is of the following format:
http://{Server}/{Application}/persistence/v1.0/{PersistenceUnit}/metadata

Below is the URI for our example:
http://localhost:8080/CustomerJPARS/persistence/v1.0/CustomerService/metadata

Response

Below is the metadata for our service.  In addition to the persistence unit name, we see links to the metadata for each of the entities in our JPA model.  Next we will take a closer look at the Customer entity.

{
    "persistenceUnitName": "CustomerService",
    "types": [
        {
            "_link": {
                "href": "http://localhost:8080/CustomerJPARS/persistence/v1.0/CustomerService/metadata/entity/Address",
                "method": "application/json",
                "rel": "Address"
            }
        },
        {
            "_link": {
                "href": "http://localhost:8080/CustomerJPARS/persistence/v1.0/CustomerService/metadata/entity/PhoneNumber",
                "method": "application/json",
                "rel": "PhoneNumber"
            }
        },
        {
            "_link": {
                "href": "http://localhost:8080/CustomerJPARS/persistence/v1.0/CustomerService/metadata/entity/Customer",
                "method": "application/json",
                "rel": "Customer"
            }
        }
    ]
}

What Can I Do with An Entity? (Entity Metadata) 

If we follow the link for one of the entities then we get the following information:
  • The entities attributes.
  • The CRUD operations that we can perform on the entity.
  • The named queries that we can perform on the entity.

GET (application/xml or application/json)

The URI to get the metadata for an entity is of the following format:
http://{Server}/{Application}/persistence/v1.0/{PersistenceUnit/metadata/entity/{Entity}

Below is the URI to get the metadata for the Customer entity:
http://localhost:8080/CustomerJPARS/persistence/v1.0/CustomerService/metadata/entity/Customer

Response 

Below is the metadata for the Customer entity.  We will be taking a closer look at the POST operation (lines 37-39) and the named query (lines 49-58).

{
    "name": "Customer",
    "attributes": [
        {
            "name": "id",
            "type": "long"
        },
        {
            "name": "firstName",
            "type": "String"
        },
        {
            "name": "lastName",
            "type": "String"
        },
        {
            "name": "address",
            "type": "Address"
        },
        {
            "name": "phoneNumbers",
            "type": "Set<PhoneNumber>"
        }
    ],
    "linkTemplates": [
        {
            "method": "get",
            "href": "http://localhost:8080/CustomerJPARS/persistence/v1.0/CustomerService/entity/Customer/{primaryKey}",
            "rel": "find"
        },
        {
            "method": "put",
            "href": "http://localhost:8080/CustomerJPARS/persistence/v1.0/CustomerService/entity/Customer",
            "rel": "persist"
        },
        {
            "method": "post",
            "href": "http://localhost:8080/CustomerJPARS/persistence/v1.0/CustomerService/entity/Customer",
            "rel": "update"
        },
        {
            "method": "delete",
            "href": "http://localhost:8080/CustomerJPARS/persistence/v1.0/CustomerService/entity/Customer/{primaryKey}",
            "rel": "delete"
        }
    ],
    "queries": [
        {
            "queryName": "findCustomersByCity",
            "returnTypes": [
                "Customer"
            ],
            "linkTemplate": {
                "method": "get",
                "href": "http://localhost:8080/CustomerJPARS/persistence/v1.0/CustomerService/query/findCustomersByCity;city={city}",
                "rel": "execute"
            },
            "jpql": "SELECT c FROM Customer c WHERE c.address.city = :city"
        }
    ]
}

Persisting an Entity

We will use the POST operation to create a new instance of the Customer entity.

POST (application/xml or application/json)

The URI to create an entity is of the following format:
http://{Server}/{Application}/persistence/v1.0/{PersistenceUnit}/entity/{Entity}

Below is the URI to create an instance of Customer:
http://localhost:8080/CustomerJPARS/persistence/v1.0/CustomerService/entity/Customer

Request 

Below is the JSON representation of our Customer data that we will post to the above URI:

{
    "id" : 1,
    "firstName" : "Jane",
    "lastName" : "Doe",
    "address" : {
        "id" : 1,
        "street" : "1 A Street",
        "city" : "Any Town"
    },
    "phoneNumbers" : [{
        "id" : 2,
        "type" : "work",
        "num" : "555-1111"
    }, {
        "id" : 3,
        "type" : "home",
        "num" : "555-2222"
    }]
}

Performing a Query

JPA-RS automatically creates URIs for each of the named queries that we defined in our JPA model:

GET (application/xml or application/json)

The URI to execute a named query is of the following format:
http://{Server}/{Application}/persistence/v1.0/{PersistenceUnit}/query/{NamedQuery;Parameters}

Below we will call the findCustomersByCity named query to find all customers from Any Town.
http://localhost:8080/CustomerJPARS/persistence/v1.0/CustomerService/query/findCustomersByCity;city=Any%20Town

Response

Below is the result of calling the named query.  We can see that relationships between entities are represented as links.  You perform a GET on the link to get the referenced data.

[
    {
        "firstName": "Jane",
        "id": 1,
        "lastName": "Doe",
        "_relationships": [
            {
                "_link": {
                    "href": "http://localhost:8080/CustomerJPARS/persistence/v1.0/CustomerService/entity/Customer/1/address",
                    "rel": "address"
                }
            },
            {
                "_link": {
                    "href": "http://localhost:8080/CustomerJPARS/persistence/v1.0/CustomerService/entity/Customer/1/phoneNumbers",
                    "rel": "phoneNumbers"
                }
            }
        ],
        "address": {
            "_link": {
                "href": "http://localhost:8080/CustomerJPARS/persistence/v1.0/CustomerService/entity/Address/1",
                "method": "GET",
                "rel": "self"
            }
        },
        "phoneNumbers": [
            {
                "_link": {
                    "href": "http://localhost:8080/CustomerJPARS/persistence/v1.0/CustomerService/entity/PhoneNumber/3",
                    "method": "GET",
                    "rel": "self"
                }
            },
            {
                "_link": {
                    "href": "http://localhost:8080/CustomerJPARS/persistence/v1.0/CustomerService/entity/PhoneNumber/2",
                    "method": "GET",
                    "rel": "self"
                }
            }
        ]
    }
]

Further Reading 

If you enjoyed this post then you may also be interested in: 

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.