如何在Grails3中获得DB连接

如何在Grails3中获得DB连接,grails,gorm,Grails,Gorm,在Grails3中获得DB连接的正确方法是什么 对于grails 2,以下代码起到了作用: ((SessionImpl) sessionFactory.getCurrentSession()).connection() // sessionFactory initialized in bootstrap 但在迁移到Grails 3之后,有时我会在日志中看到异常: java.sql.SQLException:在关闭ResultSet后不允许操作 com.mysql.jdbc.SQLError.c

在Grails3中获得DB连接的正确方法是什么

对于grails 2,以下代码起到了作用:

((SessionImpl) sessionFactory.getCurrentSession()).connection() // sessionFactory initialized in bootstrap
但在迁移到Grails 3之后,有时我会在日志中看到异常:

java.sql.SQLException:在关闭ResultSet后不允许操作 com.mysql.jdbc.SQLError.createSQLException(SQLError.java:957)位于 com.mysql.jdbc.SQLError.createSQLException(SQLError.java:896)位于 com.mysql.jdbc.SQLError.createSQLException(SQLError.java:885)位于 com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860)位于 com.mysql.jdbc.ResultSetImpl.checkClosed(ResultSetImpl.java:743)位于 com.mysql.jdbc.ResultSetImpl.findColumn(ResultSetImpl.java:1037)位于 com.mysql.jdbc.ResultSetImpl.getLong(ResultSetImpl.java:2757)位于 com.mchange.v2.c3p0.impl.NewProxyResultSet.getLong(NewProxyResultSet.java:424) 在java_sql_结果集$getLong$3.call(未知源)

这种情况发生在0.01%的请求中

  • Grails 3.2.11
  • Gorm 6.0.12

我想这取决于您需要它的位置,但您可以将数据源注入到服务中

javax.sql.DataSource dataSource
那你就可以用

dataSource.getConnection()

还应注意GORM 6中冲洗模式的变化(第1.2.1节)。如果上游保存/提交失败,您的结果集可能会意外关闭并触发一个类似这样的错误,而实际上与这一行代码没有任何关系。我会(非常暂时)回到旧的刷新模式,看看问题是否消失,然后再跟踪更多

我想这取决于您需要它的位置,但是您可以将数据源注入到服务中

javax.sql.DataSource dataSource
那你就可以用

dataSource.getConnection()
还应注意GORM 6中冲洗模式的变化(第1.2.1节)。如果上游保存/提交失败,您的结果集可能会意外关闭并触发一个类似这样的错误,而实际上与这一行代码没有任何关系。我会(非常暂时)回到旧的刷新模式,看看问题是否消失,然后再跟踪更多

从grails中,您可以获得实际的数据源bean。从中,您可以访问连接或使用它查询数据库

import groovy.sql.Sql def dataSource println "connection: ${dataSource.connection}" Sql sql = new Sql(dataSource) sql.eachRow("SELECT * FROM note") { row -> println "row: ${row}" } 导入groovy.sql.sql def数据源 println“连接:${dataSource.connection}” Sql=新Sql(数据源) eachRow(“从注释中选择*){row-> println“行:${row}” } 使用“dataSourceUnproxied”避免Hibernate事务和会话问题:

def dataSourceUnproxied def数据源未加密 从grails中,您可以获得实际的数据源bean。从中,您可以访问连接或使用它查询数据库

import groovy.sql.Sql def dataSource println "connection: ${dataSource.connection}" Sql sql = new Sql(dataSource) sql.eachRow("SELECT * FROM note") { row -> println "row: ${row}" } 导入groovy.sql.sql def数据源 println“连接:${dataSource.connection}” Sql=新Sql(数据源) eachRow(“从注释中选择*){row-> println“行:${row}” } 使用“dataSourceUnproxied”避免Hibernate事务和会话问题:

def dataSourceUnproxied def数据源未加密
对于在当前hibernate事务中执行查询,可以使用以下构造:

sessionFactory.currentSession.doWork {connection -> 
   new Sql(connection).execute(query, params)
}

对于在当前hibernate事务中执行查询,可以使用以下构造:

sessionFactory.currentSession.doWork {connection -> 
   new Sql(connection).execute(query, params)
}

数据源不共享当前事务数据源不共享当前事务