Hibernate Named Query Order By parameter

后端 未结 5 1086
悲哀的现实
悲哀的现实 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:33

    You might want to limit the sort field to the ones you have in your model. In my project I did this statically:

    public static boolean isColumnName(Object domain, String columnName) {
        Field[] fields = domain.getClass().getDeclaredFields();
        for (Field field : fields) {
            Annotation[] annotations = field.getAnnotations();
            for (Annotation annotation : annotations) {
                if (annotation instanceof Column) {
                    Column column = (Column) annotation;
                    String foundColumnName;
                    if (column.name() != null && !column.name().isEmpty()) {
                        foundColumnName = column.name();
                    } else {
                        foundColumnName = field.getName();
                    }
                    if (columnName.toUpperCase().equals(
                        foundColumnName.toUpperCase())) {
                        return true;
                    }
                }
            }
        }
        return false;
    }   
    

    Validating the field name on you DAL before concat the string into the jpql or hql you will avoid sql injection or further problems

提交回复
热议问题