不能在where子句中使用表达式

时间:2016-09-07 13:30:54

标签: spring hibernate spring-mvc spring-4 hibernate-4.x

我想实现DataTable的服务器端过滤。以下是检索列表的服务方法:

    @Override
    @Transactional
    public List<User> list(int start, int length, String search, int triIdx, String ordreTri) {

        String hql = "from User ";

        if (!search.equals("") && search != null) {

            hql = hql.concat(" where ");

            if (NumberUtils.isNumber(search))
                hql = hql.concat(" salary ");
            else
                hql = hql.concat(" lower(username) ");

            hql = hql.concat(" like lower('%:critere%') ");

        }

        if (ordreTri.equals("asc")) {
            switch (triIdx) {
                case 0:
                    hql = hql.concat(" order by username ");
                    break;
                case 1:
                    hql = hql.concat(" order by email ");
                    break;
                case 2:
                    hql = hql.concat(" order by salary ");
                    break;
                default:
                    hql = hql.concat(" order by username ");
                    break;
            }
        } else {
            switch (triIdx) {
            case 0:
                hql = hql.concat(" order by username desc");
                break;
            case 1:
                hql = hql.concat(" order by email desc");
                break;
            case 2:
                hql = hql.concat(" order by salary desc");
                break;
            default:
                hql = hql.concat(" order by username desc");
                break;
            }
        }

        Query query = sessionFactory.getCurrentSession().createQuery(hql);
        query = query.setParameter("critere",search);
        query = query.setFirstResult(start);
        query = query.setMaxResults(length);

        @SuppressWarnings("unchecked")
        List<User> listUser = (List<User>) query.list();
        return listUser;
    }

在运行时,我收到有关数据的dataTable警报错误。那我的代码有什么问题?

1 个答案:

答案 0 :(得分:0)

hql.concat(" like lower('%:critere%') ")

应该重写为:

hql.concat(" like :critere ")
query = query.setParameter("critere", "%" + search.toLowerCase(Locale. ....) + "%");