【问题标题】:How to pass sql query in grails如何在grails中传递sql查询
【发布时间】:2014-03-04 11:42:13
【问题描述】:

目前我正在使用 grails 和 MySQL。我想在单击锚标记时执行我自己的查询示例“SELECT fullName from User”。

这是我的例子

class InsertDataController {

def index() { }
def sample() {
    InsertData insertData=new InsertData();
    insertData.show();
}
}

领域类

import groovy.sql.Sql 
class InsertData {

def dataSource

def show(){
   System.out.println("demo show");
   def sql = new Sql(dataSource)
        def rows = sql.rows("SELECT fullName from User")

        rows.each { row ->
                System.out.println("demo data"+row.fullName);
            log.debug row.fullName
        }

        sql.close()
}


class User {
        String userName
        String password
        String fullName
        String toString(){
            "${fullName}"
        }
    static constraints = {
        fullName();
        userName(unique:true);
        password(password:true);
    }
}

任何人都可以建议如何解决这个问题 我想知道如何为此编写控制器和模型

谢谢你,

【问题讨论】:

  • 你不能摆脱InsertData,让你的控制器返回[ names: User.list().fullName ]
  • 我强烈建议您阅读 GORM 手册。有很多方法可用于查询数据。
  • 我正在编写该查询作为示例。实际上我想传递我自己的查询来执行。
  • 看看过滤器窗格插件 (grails.org/plugin/filterpane)。

标签: sql grails grails-2.0 gsp


【解决方案1】:
        Instead of using def sql = new Sql(dataSource) in domain class use 
         def sql = Sql.newInstance(dataSource)


        your Domain class can be modified as 

        import groovy.sql.Sql 
        class InsertData {

        def dataSource

        def show(){

            def sql = Sql.newInstance(dataSource)
                sql.eachRow("SELECT fullName from User")
    {
    println "the fullname is ${it.fullname}"
    }

        }



YOUR CONTROLLER AS

class InsertDataController {

def index() { }
def sample() {
    InsertData insertData=new InsertData();
    insertData.show();
}
}

【讨论】:

    【解决方案2】:

    InsertData 类将是一个服务 (InsertDataService),它将注入到控制器 InsertDataController。 User 类将是一个域类。

    控制器类将如下所示:

    class InsertDataController {
        def insertDataService
    
        def index() { }
        def sample() {
            insertDataService.show()
        }
    }
    

    【讨论】:

      【解决方案3】:

      你不需要注入数据源来执行你的自定义查询,在你的 show 方法中试试这个:

      User.findAll("usr.fullName from User usr")?.each{user-> 打印用户 }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-22
        相关资源
        最近更新 更多