How to Create JAX-RS Resource Entities
Let’s take a look at the creation of JAX-RS resource entities, why they should be annotated @XmlRootElement and discover how to use JAXB annotations to facilitate the serialization of JSON to entities.
A resource entity is just a Plain Old Java Object. These POJOs are the resources that we will represent, via the REST API, to a client and are usually stored in a database.
JPA Entities as Resource Entities
You can imagine that an application may have many millions of entities in its database and these can be represented with the use JAX-RS resource entities. Therefore, resource entity classes can, and often do, double up as JPA entities, capable of being persisted in the application’s database. Normally, we would use an implementation of the Java Enterprise Edition Java Persistence API, such as hibernate, to manage their persistence. These objects are annotated Entity and each field is annotated with the appropriate type designate and relationship mapping.
Using Java EE JAXB API
The only configuration that we need to do to a resource class, is to identify it as being serializable, to and from JSON. For this, we use the Java EE API called JAXB. This API is designed to bind Java objects to XML so they can be serialized and deserialized as XML documents. However, we can use JAXB annotations to do the same for JSON, and the only annotation that we required is @XmlRootElement.
So once we have created the resources we want to represent via the REST API, we just add this annotation to the class and we are done.
If you would like to learn more about using the Java EE JAX-RS API to develop client and server application while building a fully functioning bookshop application then take a look at my new JAX-RS 2.0 course. You will learn how to build and deploy a RESTful API and consume its resource in a JSF front-end client application.