Grails 中的 SQL/数据库视图 [英] SQL/Database Views in Grails

查看:26
本文介绍了Grails 中的 SQL/数据库视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有谁知道通过 Grails 访问 sql 视图的最佳方法是什么(或者这是否可行)?这样做的一种显而易见的方法是对视图使用 executeQuery 从视图中选择行集合,我们不会将其视为域对象列表.然而,即使在这种情况下,也不清楚要针对哪个域类运行 executeQuery,因为实际上我们只是使用该域类来针对完全不相关的实体(视图)运行查询.

Does anybody know what is the best approach to accessing a sql view through Grails (or if this is even possible)? It seems an obvious way of doing this would be to use executeQuery against the view to select a collection of rows from the view which we would not treat as a list of domain objects. However, even in this case it is not obvious which domain class to run executeQuery against, since really we are just using that domain class in order to run the query against a completely unrelated entity (the view).

创建一个代表视图的域类,然后我们可以只对那个域类使用 list() 是否更可取?看起来这会有问题,因为 Grails 可能希望能够插入、更新、删除和修改任何域类的表模式.

Would it be preferred to create a domain class representing the view and we could then just use list() against that domain class? It seems like there would be problems with this as Grails probably expects to be able to insert, update, delete, and modify the table schema of any domain class.

">Grails 域没有 ID 字段或具有部分 NULL 复合字段的类

[
Follow up question here: Grails Domain Class without ID field or with partially NULL composite field

推荐答案

您可以在 Grails 中使用纯 SQL,这是访问视图的首选方式 (IMO):

You can use plain SQL in Grails which is in the case of accessing a view the preferable way (IMO):

例如在您的控制器中:

import groovy.sql.Sql

class MyFancySqlController {

    def dataSource // the Spring-Bean "dataSource" is auto-injected

    def list = {
        def db = new Sql(dataSource) // Create a new instance of groovy.sql.Sql with the DB of the Grails app

        def result = db.rows("SELECT foo, bar FROM my_view") // Perform the query

        [ result: result ] // return the results as model
    }

}

和视图部分:

<g:each in="${result}">
    <tr>
        <td>${it.foo}</td>
        <td>${it.bar}</td>
    </tr>
</g:each>

我希望来源是不言自明的.文档可以在这里找到

I hope the source is self-explanatory. The Documentation can be found here

这篇关于Grails 中的 SQL/数据库视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆