Hibernate Named Query Order By parameter

后端 未结 5 1092
悲哀的现实
悲哀的现实 2020-11-29 04:42

Can anyone point me to how we can pass an order by clause as a named parameter to HQL?

Example which works:

select tb from TransportBooking as tb

an         


        
5条回答
  •  北荒
    北荒 (楼主)
    2020-11-29 05:29

    Try storing the named query without the order by clause, getting the query string and adding the order by clause pieces at run time.

    Brian Fields explained it in his blog: http://brainfields.blogspot.com/2009/08/order-by-in-hibernate-named-queries.html

    I have packaged the idea up for my project :

    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 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;
    }
    

提交回复
热议问题