REST Test – Generate REST Service

Use the Netbeans New, RESTful Web Services from Entity Classes, to create the required REST service code.
This has a small impact on the AnEntity class, adding the JAXB @XmlRootElement annotation. The key class created here though is AnEntityFacadeREST.java. I made two tweaks to the generated code at this point.

1. Replace the magic string constants values by the MediaType.APPLICATION_XML and MediaType.APPLICATION_JSON constants; just for personal preference.
2. Amend the @POST (create) service to return the URL of the created resource.

In the generated class file AbstractFacade.java, the create method was changed to:

public T createEntity(T entity) {
  EntityManager entityManager = getEntityManager();
  entityManager.persist(entity);
  entityManager.flush();
  return entity;
}

Notice that this performs an entityManager.flush() in order to generate the entity’s id.
Just for consistency, the edit and remove method names were changed to editEntity and removeEntity.

Then the REST service class file (AnEntityFacadeREST.java) the create method was changed to:

@POST
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response create(AnEntity entity) {
  AnEntity newEntity = super.createEntity(entity);
  URI newEntityUri = uriInfo.getRequestUriBuilder().path(newEntity.getId().toString()).build();
  return Response.created(newEntityUri).entity(newEntity).contentLocation(newEntityUri).build();
}

together with adding the class variable:

@Context
UriInfo uriInfo;

REST Test - Create JPA Entity REST Test - Unit Tests and Coverage Reporting

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.