Practical RESTful persistence
EclipseLink provides a JPA-RS implementation. Let’s see what hides behind this.
The use case is a web application with the main logic inside the browser and a backend providing only persistency. We want to provide a REST API to that persistence.
To do this, let’s create a stack with the browser at the top and the database at the botom:
- EclipseLink MOXy
- EclipseLink JPA
The bottom part from database to Java is well-known. So we won’t discuss too much about it.
EclipseLink uses the binding part of its JAXB implementation to bind to JSON (JSON-P specification only supports parsing and generation but no binding).
The challenges of translating database data into JSON content are the following:
- composite keys/embedded key classes
- byte code weaving that is done by JPA comes into the way when it comes to the JAXB marshalling
- bidirectional/cyclical relationships because one of the side must be cut off when marshalling, which means that the unmarshalling will lose one-side of the relationship
To fix the last of these three issues, EclipseLink introduces a new annotation 0XmlInverseReference which induces EclipseLink to recreate the missing side of the relation base on the other direction.
JPA-RS is capable of creating the JAX-RS endpoint, creating a default JAXB mapping.
EclipseLink JPA-RS comes as a JavaEE fragment, which means that integrating it is just a matter of making it available in the classpath.
Current approach of fetching one entity level at a time and providing links to the next level entities is kinda naive.
It should be able to select only the wanted information and to provide linked entites if wanted.
Currently, security is not implemented with enough grain: all entities are exposed.
As a conclusion, this tool allows to gain a lot of time if all what is needed is to provide a JAX-RS layer above an existing persistence unit.