按参数休眠命名查询顺序

2022-09-02 00:57:04

任何人都可以向我指出我们如何将订单通过子句作为命名参数传递给HQL?

有效示例:

select tb from TransportBooking as tb

and TIMESTAMP(tb.bookingDate, tb.bookingTime) >= current_timestamp() order by tb.bookingDate

不起作用的示例:

select tb from TransportBooking as tb

and TIMESTAMP(tb.bookingDate, tb.bookingTime) >= current_timestamp() order by :order

答案 1

不支持,输入参数只允许在 和 子句中使用,不能对子句使用参数。或者,如果我改写,您不能对列使用参数,只能对值使用参数。因此,要么:WHEREHAVINGORDER BY

  • 具有尽可能多的命名查询排序顺序
  • 将排序字符串连接到查询字符串
  • 使用条件查询

答案 2

尝试在不使用 order by 子句的情况下存储命名查询,获取查询字符串并在运行时按子句段添加 order by 子句。

布莱恩·菲尔兹(Brian Fields)在他的博客中解释了这一点:http://brainfields.blogspot.com/2009/08/order-by-in-hibernate-named-queries.html

我已经为我的项目打包了这个想法:

private static final Pattern badQueryPattern = Pattern.compile("[^\\p{ASCII}]*");

public static String getNamedQueryString(EntityManager em, String queryName) throws SQLException {
    Query tmpQuery = em.createNamedQuery(queryName);
    SQLQuery sqlQuery = tmpQuery.unwrap(SQLQuery.class);
    String queryString = sqlQuery.getQueryString();
    if (badQueryPattern.matcher(queryString).matches()) {
        throw new SQLException("Bad query string.");
    }

    return queryString;
}


public static Query getNamedQueryOrderedBy(EntityManager em, String queryName, Map<String, Boolean> columnNames) throws SQLException {

    StringBuilder sb = new StringBuilder();
    sb.append(ORDER_BY_CLAUSE_START);

    int limit = columnNames.size();
    int i = 0;
    for (String columnName: columnNames.keySet()) {
        sb.append(columnName);

        if (columnNames.get(columnName))
            sb.append(" ASC");
        else
            sb.append(" DESC");

        if (i != (limit - 1)) {
            sb.append(", \n");
        }
    }
    Query jpaQuery = em.createNativeQuery( getNamedQueryString(em, queryName)
                + sb.toString() 
                );

    return jpaQuery;
}

推荐