在前一篇文章里,我们学习了在Grails应用中使用Hibernate SQL。同样的,我们也可以使用Groovy SQL执行自定义的SQL语句。我们必须创建一个groovy.sql.Sql
实例来执行SQL代码。最简单的方式就是将javax.sql.DataSources
作为一个构造函数的参数传给groovy.sql.Sql
。在Grails应用的上下文中,已经存在一个DataSource
实例,我们只需要将其注入到我们的代码中。在Grails应用中必须使用dataSource
来引用那个默认的数据源。
在下面的样例中,我们使用Groovy SQL执行一个自定义查询。请注意,在Grails service PersonService
中,我们定义了一个属性dataSource
,Grails会自动注入一个DataSouce
实例。
package com.mrhaki.grails
import groovy.sql.Sql
import groovy.sql.GroovyRowResult
class PersonService {
// Reference to default datasource.
def dataSource
List<GroovyRowResult> allPersons(final String searchQuery) {
final String searchString = "%${searchQuery.toUpperCase()}%"
final String query = '''\
select id, name, email
from person
where upper(email collate UNICODE_CI_AI) like :search
'''
// Create new Groovy SQL instance with injected DataSource.
final Sql sql = new Sql(dataSource)
final results = sql.rows(query, search: searchString)
results
}
}
在Grails应用中,可以将groovy.sql.Sql
实例定义为一个Spring bean。这样,我们就可以将Sql
实例注入到我们的service中了。在grails-app/conf/spring/resources.groovy
,我们定义一个Sql
bean:
// File: grails-app/conf/spring/resources.groovy
beans = {
// Create Spring bean for Groovy SQL.
// groovySql is the name of the bean and can be used
// for injection.
groovySql(groovy.sql.Sql, ref('dataSource'))
}
现在我们使用groovySql
bean重写上的例子:
package com.mrhaki.grails
import groovy.sql.GroovyRowResult
class PersonService {
// Reference to groovySql defined in resources.groovy.
def groovySql
List<GroovyRowResult> allPersons(final String searchQuery) {
final String searchString = "%${searchQuery.toUpperCase()}%"
final String query = '''\
select id, name, email
from person
where upper(email collate UNICODE_CI_AI) like :search
'''
// Use groovySql bean to execute the query.
final results = groovySql.rows(query, search: searchString)
results
}
}
以上使用的是Grails 2.3.7。