【问题标题】:Order By Value In Collection With Database Query In Grails使用 Grails 中的数据库查询在集合中按值排序
【发布时间】:2013-10-11 21:11:41
【问题描述】:

我的最新发明是一个系统,您可以在其中实时跟踪世界各地餐厅的华夫饼。

为了实现这一点,我有一个Waffle,其中有许多Condiments,其中任何一个可能是也可能不是Waffle 上的presentWaffletable number 它当前处于打开状态,并且属于 Restaurant,它有许多 Names 被翻译成不同的 languages。

从技术上讲,我需要获取每个Waffle where Waffle.shape == 'square' 并按RestaurantName where Waffle.Restaurant.Names.language == 'en' 排序并显示Condiment.present 是否为真。

Restaurant.Names = ['language':'en', 'name':'Waffle House'], ['language':'fr', 'name':'Le Waffle House'], ['语言':'de','名称':'Das Waffle House'] 按方形过滤 ============================== (升序) 五 餐厅餐桌#糖浆黄油蛋黄酱 -------------------------------------------------- -------- 丹尼的 42 Y Y N 丹尼的 27 N N N 丹尼的 11 Y Y N IHOP 10 是 N N IHOP 7 N N N 华夫饼屋 10 Y Y Y

这是类的简化版本:

class Condiment {
    int condimentId
    boolean present
    Waffle waffle
    static belongsTo = [Waffle]
}

class Waffle {
    int waffleId
    int tableNumber
    String shape
    Restaurant restaurant
    static belongsTo = [Restaurant]
    static hasMany = [condiments:Condiment]
}

class Restaurant {
    int restaurantId
    static hasMany = [waffles:Waffle, names:Name]
}

class Name {
    String name
    String language
    static hasMany = [restaurants:Restaurant]
}

如果可能,我想在 GORM 中执行此操作,但 HQL 也是可以接受的。这与 Grails 2.3 一起使用。请记住,这是分页的,因为世界上有数百万 Waffles,如果不是更多的话!

【问题讨论】:

    标签: grails collections hql grails-orm


    【解决方案1】:

    基于标准:

    def waffles = Waffle.createCriteria().list(offset: 0, max: 100){
        eq('shape', 'square')
        restaurant{
            names{
                eq('language', 'en')
                order('name', 'asc')
            }
        }
        condiments{
            eq('present', true)
        }
    }
    

    基于 HQL:

    def query = """
                   select w from Waffles as w \
                   inner join w.restaurant as r \ 
                   inner join w.condiments as c \
                   inner join r.names as n \
                   where w.shape = :shape \
                   and n.language = :lang \
                   and c.present is true
                """
    
    def waffles = Waffle.executeQuery(query,[shape: 'square', lang: 'en', 
                                               max: 100, offset: 0])
    

    将为您提供前 100 个华夫饼。

    基于 HQL 的方法将是有效的,因为不会急切地获取餐厅、名称和调味品,如使用上述条件时会出现这种情况。

    lang 更改为法语的“fr”。

    【讨论】:

    • 我的华夫饼分好了!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多