加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Grails精华:使用Groovy SQL

发布时间:2020-12-14 16:50:25 所属栏目:大数据 来源:网络整理
导读:在前一篇文章里,我们学习了在Grails应用中使用Hibernate SQL。同样的,我们也可以使用Groovy SQL执行自定义的SQL语句。我们必须创建一个 groovy.sql.Sql 实例来执行SQL代码。最简单的方式就是将 javax.sql.DataSources 作为一个构造函数的参数传给 groovy.s

在前一篇文章里,我们学习了在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,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。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读