Grails精华:使用Groovy SQL

在前一篇文章里,我们学习了在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,我们定义一个Sqlbean:

	// 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'))
	 
	}

现在我们使用groovySqlbean重写上的例子:

	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。

转载于:https://my.oschina.net/zjzhai/blog/223749

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值