grails按长度排序

时间:2015-10-31 08:56:18

标签: hibernate grails groovy

任何身体都能帮忙吗?我正在使用hibernate与Grails结合使用。

我想通过findby或createCriteria

执行此sql语句
select user.username, user.email from user where user.username like something order by length(username)

语法顺序按长度(用户名)

出现问题

我试过这个,但得到验证sql语法错误:

def c = User.createCriteria();
List<User> user = c.list  {
    or {
        ilike("username", search)
        ilike("email", search)
    }

    order(length("username"))
    //order("length(username)")
    //order("username.length()")
    //sqlRestriction("order by length(username)")
}

和这个

List<User> user = User.findAllByUsernameIlikeOrEmailIlike(search, search, [sort: "length(username)"])

3 个答案:

答案 0 :(得分:3)

使用条件查询您运气不佳,因为order(String propertyName)无法访问由sqlProjection(java.lang.String sql, java.lang.String columnAlias, org.hibernate.type.Type type创建的别名。以下是usernameemail以及username的长度的投射方式:

def rows = User.withCriteria {
    or {
        ilike("username", search)
        ilike("email", search)
    }

    projections {
        property('username')
        property('email')
        sqlProjection('length(username) as usename_len', 'name_len', LONG)
    }
}

上面的条件查询将返回List List,内部List包含三列。但是,您无法按name_len排序作为查询的一部分。您必须在Groovy中对List进行排序:

list.sort { it[2] }
// or, and alternative for Groovy >= 2.4.4
list.toSorted { it[2] }

替代方案:HQL

可以实现您正在寻找的内容的替代方案是HQL:

def rows = User.executeQuery('SELECT username, email, length(username) as name_len FROM User ORDER BY name_len')

上面的HQL查询不仅返回三列,还按length(username)排序。另外,HQL可以项目 User实例本身。相反,条件查询只能投影属性。这意味着您可以获得List个已排序的User个实例。

def users = User.executeQuery('SELECT u FROM User as u ORDER BY length(username)')

答案 1 :(得分:0)

你能这样试试吗?

    'use strict';

// Declare app level module which depends on views, and components
angular.module('myApp', [
    'ngRoute'
])
    .constant('STORAGE_NAME', 'USER_CARS')
    .config(configStorage)
    .config(configRoutes)

.controller('carsCtrl', ['$scope', '$http', 'carsSrv',
    function($scope, $http, carsSrv) {
        $scope.view = "Cars";
        $http.get('cars/cars.json')
            .success(function(data) {

                $scope.cars = data;

                $scope.addCar = function(id, title, color, description, image) {
                    carsSrv.addUserCar(id, title, color, description, image);
                };

            })
            .error(function() {
                alert("can not get data from cars.json");
            });
    }
])

.controller('homeCtrl', ['$scope',

    function($scope) {
        $scope.view = "Home";
    }
])

.controller('loginCtrl', ['userSrv', '$scope',
    function(userSrv, $scope) {
        $scope.view = "Login";
        $scope.userLogin = function() {
            userSrv.login();

        }
        $scope.userLogout = function() {
            userSrv.logout();

        }

    }
])

.controller('profileCtrl', ['$scope', 'carsSrv',
    function($scope, carsSrv) {
        $scope.view = "Profile";
        $scope.userCars = carsSrv.getCars();


    }
]);

function configStorage(storageSrvProvider, STORAGE_NAME) {
    console.log(storageSrvProvider);
    storageSrvProvider.configStorageName(STORAGE_NAME);
}

function configRoutes($routeProvider) {
    $routeProvider

    .when('/cars', {
        templateUrl: 'views/cars.html',
        controller: 'carsCtrl',
        secure: true
    })

    .when('/profile', {
        templateUrl: 'views/profile.html',
        controller: 'profileCtrl',
        secure: true
    })

    .when('/home', {
        templateUrl: 'views/home.html',
        controller: 'homeCtrl',
        secure: false
    })

    .when('/login', {
        templateUrl: 'views/login.html',
        controller: 'loginCtrl',
        secure: false
    })



    .otherwise({
        redirectTo: '/home'
    });
}

var appRun = function($rootScope, $location, $userSrv) {
    $rootScope.on('$routeChangeStart', function(event, next) {
        if (next.secure && !userSrv.checkLoginUser()) {
            $location.path('/login');
        }
    });
};

答案 2 :(得分:0)

您可以尝试这种方式......按升序排列

fetchRequest.fetchBatchSize = 1_000_000

对于降序,只需改变你的排序

 List<User> user = User.findAllByUsernameIlikeOrEmailIlike(username, email).sort{it.username.length}