Hibernate order by with nulls last

前端 未结 7 2093
谎友^
谎友^ 2020-11-30 03:42

Hibernate used with PostgreSQL DB while ordering desc by a column puts null values higher than not null ones.

SQL99 standard offers keyword \"NULLS LAST\" to declare

7条回答
  •  遥遥无期
    2020-11-30 04:19

    Here's my update to the class by (Pascal Thivent):

    for (int i = 0; i < orderByNames.length; i++) {
        if (orderByNames[i].trim().length() > 0) {
            String orderName = orderByNames[i].trim().toLowerCase();
            if (orderName.contains("desc")) {
                orderByNames[i] = orderName.replace("desc", "desc NULLS LAST");
            } else {
                orderByNames[i] = orderName.replace("asc", "asc NULLS FIRST");
            }
        }
    }
    

    This fixes the problem:

    This breaks if sql has limit/offset after order by – Sathish Apr 1 '11 at 14:52

    Also here's how you can use this within JPA (hibernate):

    Session session = entityManager.unwrap(Session.class);
    Session nullsSortingProperlySession = null;
    try {
        // perform a query guaranteeing that nulls will sort last
        nullsSortingProperlySession = session.getSessionFactory().withOptions()
            .interceptor(new GuaranteeNullsFirstInterceptor())
            .openSession();
    } finally {
        // release the session, or the db connections will spiral
        try {
            if (nullsSortingProperlySession != null) {
                nullsSortingProperlySession.close();
            }
        } catch (Exception e) {
            logger.error("Error closing session", e);
        }
    }
    

    I've tested this on postgres and it fixes the 'nulls are higher than non-nulls' issue that we were having.

提交回复
热议问题