1

我正在创建一个 Jax-RS 资源。我想返回响应中的记录总数。我正在使用命名查询和标题函数来添加特定的“计数”变量,如下所示:

@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();
    }
}

我想知道是否有更好的方法来计算和返回找到的记录总数?

4

1 回答 1

1

你可以看看这个链接!它处理 ListResource 以构造返回的 JSON 数据:http: //www.twilio.com/docs/api/rest/response#response-formats-list

http://twilio.github.io/twilio-java/com/twilio/sdk/resource/ListResource.html

于 2015-03-09T12:00:48.957 回答