创建条件语句,使用一个查询获取结果和行计数

时间:2016-12-28 15:33:05

标签: java postgresql hibernate

我尝试在单个查询中获取结果以及行计数以进行分页。

这是我到目前为止所得到的:

public List<User> getUsers(int page, int size, boolean somecondition) {


    Criteria criteria = getSession().getCurrentSession().createCriteria(User.class);

    ProjectionList projectionList = Projections.projectionList();

    projectionList.add(Projections.property("name").as("name"));
    projectionList.add(Projections.property("createdAt").as("createdAt"));
    projectionList.add(Projections.property("id").as("id"));
    projectionList.add(Projections.rowCount());
    projectionList.add(Projections.groupProperty("id"));

    criteria.setProjection(projectionList);

    // pseudo Restrictions added
    if (somecondition) {
        criteria.add(Restrictions.isNotNull("email"));
    }

    if (somecondition) {
        criteria.add(Restrictions.isNotNull("name"));
    }

    // Now here do something to get the row count without doing a second query
    long count;

    ScrollableResults scrollableResults = criteria.scroll();
    scrollableResults.last();
    count = scrollableResults.getRowNumber() + 1;
    scrollableResults.close();

    log.info("users count : {}", count);

    criteria.setMaxResults(size);
    criteria.setFirstResult(page);

    criteria.setResultTransformer(new AliasToBeanResultTransformer(User.class));
    List<User> users = criteria.list();

    users.forEach(u -> log.info(u.toString()));

    return users;
}

read我可以使用ScrollableResults来获取没有第二个查询的行数,但这不起作用,我仍然在控制台中看到有2个查询。

我没有尝试获得总结果,获得满足条件的结果计数非常重要。

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

这是我用一次查询得到计数和结果的方式。

@RestControllerAdvice
@RequestMapping(produces = "application/json")
public class DefaultExceptionHandler extends ResponseEntityExceptionHandler {

    // This method handles constraint violation exception raised by DB. 
    // Similarly other type exceptions like custom exception and HTTP status related 
    //exception can be handled here.
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(value = HttpStatus.CONFLICT)
    public Map<String, String> handleConstraintViolationException(ConstraintViolationException ex) {
    // write your own logic to return user friendly response 
   }

   // Below method is to handle _SqlExceptionHelper_ exception
    @ExceptionHandler(SqlExceptionHelper.class)
    @ResponseStatus(value = HttpStatus.CONFLICT)
    public Map<String, String> handleConstraintViolationException(SqlExceptionHelper ex) {
    // write your own logic to return user friendly response 
   }



}

它给出了不受限制和偏移影响的行的总计数。 希望它有所帮助!