How a JEE6 enterprise application that offers REST web services should be organized?

design-patterns, jakarta-ee, java, jax-rs, rest

Solution

Below is an example of a JAX-RS service implemented as a session bean using JPA for persistence and JAXB for messaging might look like. (note an `EntityManager` is injected onto the session bean, why do you want to avoid this kind of behaviour?):

package org.example;

import java.util.List;

import javax.ejb.*;
import javax.persistence.*;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;

@Stateless
@LocalBean
@Path("/customers")
public class CustomerService {

    @PersistenceContext(unitName="CustomerService",
                        type=PersistenceContextType.TRANSACTION)
    EntityManager entityManager;

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

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

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

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

    @GET
    @Produces(MediaType.APPLICATION_XML)
    @Path("findCustomersByCity/{city}")
    public List<Customer> findCustomersByCity(@PathParam("city") String city) {
        Query query = entityManager.createNamedQuery("findCustomersByCity");
        query.setParameter("city", city);
        return query.getResultList();
    }

}

If you want to use the same domain objects on the server and client side. Then I would provide the JPA mappings via XML rather than annotations to avoid a classpath depedency on the client.

For More Information

- Part 1 - Data Model

- Part 2 - JPA

- Part 3 - JAXB (using MOXy)

- Part 4 - RESTful Service (using an EJB session bean)

- Part 5 - The client

UPDATE

META-INF/persistence.xml

The persistence.xml file is where you specify a link to the XML file that contains the JPA mappings:

<persistence-unit name="CustomerService" transaction-type="JTA">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <jta-data-source>CustomerService</jta-data-source>
    <mapping-file>META-INF/orm.xml</mapping-file>
</persistence-unit>

META-INF/orm.xml

It is in this file that you would add the XML representation of the JPA metadata.

<?xml version="1.0" encoding="UTF-8"?>
<entity-mappings
    version="2.0"
    xmlns="http://java.sun.com/xml/ns/persistence/orm"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm http://java.sun.com/xml/ns/persistence/orm_2_0.xsd">
    <entity class="org.example.Customer">
         <named-query name="findCustomersByCity">
            <query>SELECT c FROM Customer c WHERE c.address.city = :city</query>
         </named-query>
         <attributes>
            <id name="id"/>
            <basic name="firstName">
                <column name="FIRST_NAME"/>
            </basic>
            <basic name="lastName">
                <column name="LAST_NAME"/>
            </basic>
            <one-to-many name="phoneNumbers" mapped-by="customer">
                <cascade>
                    <cascade-all/>
                </cascade>
            </one-to-many>
            <one-to-one name="address" mapped-by="customer">
                <cascade>
                    <cascade-all/>
                </cascade>
            </one-to-one>
         </attributes>
    </entity>
    <entity class="org.example.Address">
        <attributes>
            <id name="id"/>
            <one-to-one name="customer">
                <primary-key-join-column/>
            </one-to-one>
        </attributes>
    </entity>
    <entity class="org.example.PhoneNumber">
        <table name="PHONE_NUMBER"/>
        <attributes>
            <id name="id"/>
            <many-to-one name="customer">
                <join-column name="ID_CUSTOMER"/>
            </many-to-one>
        </attributes>
    </entity>
</entity-mappings>

For More Information

- Creating a RESTful Web Service - Part 2/5 (XML Metadata)

Problem

Since a month ago i am studying restful web services really hard. Now that i did practice the Syntax and i understand the concepts, i decided to make a very simple enterprise application that includes EJB, JPA and REST. I am making a big effort in trying to understand what is the best way to organize this kind of system. Ill appreciate a lot if someone with experience in the field could give me some tips on what would be the best practice, and how can i solve my current problem. Let me show you this image please. Sorry i cannot get better resolution(Use Ctrl+ Mouse Scroll Up to zoom): As you can see this is a very simple enterprise app, that has 2 modules. This application does not use CDI( I want to achieve my goal without CDI help and) When some client(Any inter-operable client) sends a @GET with some parameters the REST service should pass those parameters to the EJB module which will search in the database and send back the appropiate data. At the end the service will automatically marshal with the help of JAXB and send the .XML back to the client. My problems are the following: - I get a ClassCastException because the entity in the that is in the EJB module is not compatible with the JAXB class in the WebModule(Even if their variables are the same) - I don't know how things should be organized so the front end can marshal and unmarshal those entities. - Should maybe the entity class be in the front end combined with the JAXB mapping? If then, there will not be really need for the EJB module. But the thing is, i want the EJB module because i often do my CRUD operations there. - What about exposing the EJB as a REST web service(making a hybrid)? Do you think this is a good idea? How can it help me? - Again if i create a hybrid of JAXRS+EJB in the web module, i will must create then my JPA entities in the front end and that is a thing i never did before. Do you think it is a good practice? - What do you suggest? What is often the way the Enterprise applications that use REST web services are organized?

Original source