Grails的SQL查询 [英] Grails sql queries
问题描述
def example = {
def temp = ConferenceUser.findAllByUser(User .get(session.user))
[temp:temp]
}
解释我的问题:
尽管动态查找器非常易于使用且学习速度快,但我必须替换我的网站的动态查找器以查找SQL查询,因为这是一项要求。因为我不太了解SQL,所以我的主要问题是:a)我使用SQLS数据库,驱动程序和数据源配置良好,我的网站工作正常就像现在这样。如果我想替换sql语句的findAllByUser,我应该这样做:
def dataSource
$ p $ b>
...
def db = new Sql(dataSource)
def temp = db.rows(SELECT ...)
b)那会起作用吗?我的意思是,如果我使用findAllByUser,临时对象将成为一个列表,并且是否需要打开一个到数据库的连接=? 方案
是的,用grails你可以做简单的sql和hql查询。 HQL是'hibernate查询语言',允许你编写类似sql的语句,但是使用你的域类和属性来代替表名和列名。要做一个hql查询,请执行以下操作:
def UserList = ConferenceUser.executeQuery('from ConferenceUser cu其中cu.user =? ',[user]),
这里有一个参数化查询 - executeQuery看到?在hql字符串中,并将数组中的参数替换为方法的第二个参数(本例中为 [user]
)。
请参阅
http:/ /grails.org/doc/latest/ref/Domain%20Classes/executeQuery.html
你可以看到如何使用Grails进行sql查询
Imagine I have something like this:
def example = {
def temp = ConferenceUser.findAllByUser(User.get(session.user))
[temp: temp]
}
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) 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) 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 =?
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]),
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.
See http://grails.org/doc/latest/ref/Domain%20Classes/executeQuery.html
and you can see this on how to do sql queries with Grails
Sql query for insert in grails
这篇关于Grails的SQL查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!