我尝试用以下代码在Grails中执行原始SQL:
class PlainSqlService {
def dataSource // the Spring-Bean "dataSource" is auto-injected
def newNum = {
def sql = new Sql(dataSource) // Create a new instance of groovy.sql.Sql with the DB of the Grails app
def q = "SELECT a.xaction_id, a.xdin FROM actions a WHERE a.is_approved = 0"
def result = sql.rows(q) // Perform the query
return result
}
}但我在运行时得到了这个异常。
sql对象不是null!
我如何调试它?
2011-02-13 15:55:27,507 [http-8080-1] ERROR errors.GrailsExceptionResolver - Exception occurred when processing request: [GET] /moderator/login/index
Stacktrace follows:
java.lang.NullPointerException
at moderator.PlainSqlService$_closure1.doCall(PlainSqlService.groovy:17)
at moderator.PlainSqlService$_closure1.doCall(PlainSqlService.groovy)
at moderator.LoginController$_closure1.doCall(LoginController.groovy:29)
at moderator.LoginController$_closure1.doCall(LoginController.groovy)
at java.lang.Thread.run(Thread.java:662)发布于 2011-02-13 16:43:57
很难从您所提供的有限代码中分辨出发生了什么,但是有一些事情需要检查。服务是像这里为dataSource注入的类范围字段"def plainSqlService“注入控制器,还是调用new PlainSqlService()?如果您正在创建一个新实例,那么dataSource bean不会被注入,groovy.sql.Sql构造函数不会失败,但是查询会失败。
要尝试的一件事是grails clean --每当这样的事情不能工作时,完整的重新编译通常会有所帮助。
一个重要但不相关的问题--您不应该在服务中使用闭包。控制器和标签要求用闭包实现操作和标记,但是服务只是Groovy中定义的Spring。Spring对闭包一无所知,因为它们只是Groovy执行的一个字段,就好像它是一个方法一样,所以您期望从Spring获得的任何代理(特别是事务性行为,但也包括安全性和其他特性)都不会发生,因为Spring只查找方法。
因此,newNum应声明为:
def newNum() {
...
}https://stackoverflow.com/questions/4984016
复制相似问题