I am creating a Jax-RS resource. I would like to return the total number of records in the response. I am using a named query and a header function to add a specific "Count" variable like following:
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response findAll(
@QueryParam("offset") int offset,
@QueryParam("limit") int limit) {
EntityManager em = factory.createEntityManager();
Query query;
try {
query = em.createNamedQuery("User.getCount");
String count = ((Long) query.getSingleResult()).toString();
query = em.createNamedQuery("User.findAll");
List<T> list = query.setFirstResult(safeOffset(offset))
.setMaxResults(safeLimit(limit))
.getResultList();
return Response.ok(new GenericEntity<List<User>>(list) {})
.header("Count", count)
.build();
} catch (Exception e) {
return Response.serverError().build();
} finally {
em.close();
}
}
I was wondering if there is a better way to calculate and return total number of records found?
You can have a look at this link ! It deals with ListResource to structure the JSON data returned : http://www.twilio.com/docs/api/rest/response#response-formats-list
http://twilio.github.io/twilio-java/com/twilio/sdk/resource/ListResource.html