欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 运维知识 > 数据库 >内容正文

数据库

Grails精华:使用Groovy SQL

发布时间:2025/3/20 数据库 68 豆豆
生活随笔 收集整理的这篇文章主要介绍了 Grails精华:使用Groovy SQL 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

2019独角兽企业重金招聘Python工程师标准>>>

在前一篇文章里,我们学习了在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.grailsimport groovy.sql.Sqlimport groovy.sql.GroovyRowResultclass PersonService {// Reference to default datasource.def dataSourceList<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.groovybeans = {// 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.grailsimport groovy.sql.GroovyRowResultclass PersonService {// Reference to groovySql defined in resources.groovy.def groovySqlList<GroovyRowResult> allPersons(final String searchQuery) {final String searchString = "%${searchQuery.toUpperCase()}%"final String query = '''\select id, name, emailfrom personwhere 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

与50位技术专家面对面20年技术见证,附赠技术全景图

总结

以上是生活随笔为你收集整理的Grails精华:使用Groovy SQL的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。