Grails sql 查询 [英] Grails sql queries
问题描述
想象一下我有这样的事情:
Imagine I have something like this:
def example = {
def temp = ConferenceUser.findAllByUser(User.get(session.user))
[temp: temp]
}
解释我的问题:尽管动态查找器非常易于使用且易于学习,但我必须将我网站的动态查找器替换为 sql 查询,因为这是一项要求.由于我不太了解 SQL,我的主要问题是:
Explaining my problem: Although dynamic finders are very easy to use and fast to learn, I must replace dynamic finders of my website for sql queries because it is a requirement. As I don't understand SQL that much, my main questions are:
a) 我正在使用 SQLS 数据库,驱动程序和数据源配置良好,我的网站现在可以正常工作.如果我想替换 sql 语句的findAllByUser",我应该这样做:
a) I am using an SQLS database, with the drivers and datasource good configured and my website works as it is right now. If I want to replace the "findAllByUser" for an sql statement, should i do something like this:
def dataSource
...
def db = new Sql(dataSource)
def temp = db.rows("SELECT ... ")
b) 那会起作用吗?我的意思是,如果我使用findAllByUser",临时对象将是一个列表,我是否需要打开与数据库的连接=?
b) And that will work? I mean, the temp object will be a list as it is if I use "findAllByUser", and do I need to open a connection to the database =?
推荐答案
是的,使用 grails,您可以执行普通的 sql 和 hql 查询.HQL 是休眠查询语言",允许您编写类似 sql 的语句,但使用域类和属性而不是表名和列名.要进行 hql 查询,请执行类似
yes, with grails you can do both plain sql and hql queries. HQL is 'hibernate query language' and allows you to write sql-like statements, but use your domain classes and properties instead of the table names and column names. To do an hql query, do something like
def UserList = ConferenceUser.executeQuery('from ConferenceUser cu where cu.user = ?', [user]),
这里有一个参数化查询——executeQuery 看到 ?在 hql 字符串中,并为您替换作为方法的第二个参数的数组中的参数(在本例中为[user]
).
what you have here is a parameterized query -- executeQuery sees the ? in the hql string and substitutes the arguments in the array that is the second parameter to the method([user]
in this case) for you.
见http://grails.org/doc/latest/ref/Domain%20类/executeQuery.html
你可以看到这个关于如何使用 Grails 进行 sql 查询
and you can see this on how to do sql queries with Grails
这篇关于Grails sql 查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!