如何使用HQL和find函数grails(GORM)进行选择?

时间:2017-03-03 10:05:57

标签: java hibernate grails hql gorm

我不熟悉grails并通过在线提供的文档进行学习。

在阅读find()函数时,有一件事让我很困惑。

Book.find(String query) // pass the HQL, However there are various overloaded variants.

现在,如果我像这样使用这个find()函数。

Category.find("from Category as cat where cat.id = ? ", [5L]) //result is fine.

我的分类

class Category {

    String title;
    String description
    String image
    static constraints = {
        title blank: false, nullable: false
        description blank: true, nullable: true
    }
}

但如果我尝试了这个HQL查询

 Category.find("select  cat.description from Category as cat where cat.id = ? ", [5L])
//or this query.
 Category.find("select description from Category as cat where cat.id = ? ", [5L])

它引发了一个例外: -

Invalid query [select  cat.description from Category as cat where cat.id = ? ] for domain class [class com.ecommerce.domain.Category]. Stacktrace follows:
Message: Invalid query [select  cat.description from Category as cat where cat.id = ? ] for domain class [class com.ecommerce.domain.Category]

所以,如果我的HQL有任何问题请评论.....

或 您可以回答如何使用find(String query)

的select语句

1 个答案:

答案 0 :(得分:1)

单个结果:

Category.find("from Category cat where cat.id = ?", [5L])?.description

或倍数:

Category.find("from Category cat where cat.id = ?", [5L]).collect{ it.description }