【问题标题】:If I use groovy sql class in grails, does it use the grails connection pooling?如果我在 grails 中使用 groovy sql 类,它是否使用 grails 连接池?
【发布时间】:2012-02-17 02:48:47
【问题描述】:

来自以下 sql 文档中的示例。如果我使用这些方法中的任何一种在 grails 服务类的中间创建一个 sql 实例,它会使用 grails 连接池吗?它会参与任何交易能力吗?我需要自己关闭连接吗?还是会自动回到池中?

def db = [url:'jdbc:hsqldb:mem:testDB', user:'sa', password:'', driver:'org.hsqldb.jdbcDriver']
  def sql = Sql.newInstance(db.url, db.user, db.password, db.driver)

或者如果您有一个现有连接(可能来自连接池)或数据源,请使用以下构造函数之一:

  def sql = new Sql(datasource)

现在您可以调用 sql,例如创建表:

 sql.execute '''
        create table PROJECT (
          id integer not null,
          name varchar(50),
          url varchar(100),
        )
 '''

【问题讨论】:

    标签: sql grails groovy


    【解决方案1】:

    如果你执行:

    Sql.newInstance(...)
    

    您将创建一个新连接并且您没有使用连接池。

    如果要使用连接池,可以使用以下命令创建Service:

    grails create-service org.foo.MyService
    

    然后,在您的 MyService.groovy 文件中,您可以按如下方式管理事务:

    import javax.annotation.PostConstruct
    
    class MyService {
        def dataSource              // inject the datasource
        static transactional = true // tell groovy that the service methods will be transactional
    
    
        def doSomething() {
           sql = new Sql(dataSource)
           //rest of your code
        }
    }
    

    更多详情可以阅读:http://grails.org/doc/2.0.x/guide/services.html

    编辑:

    要管理多个数据源,您可以根据您的 Grails 版本执行以下操作之一。

    如果您使用的 Grails 版本高于 1.1.1(不是 2.x),您可以使用以下插件:

    http://grails.org/plugin/datasources
    

    如果您使用的是 Grails 2.x,则可以使用开箱即用的支持:

    http://grails.org/doc/2.0.0.RC1/guide/conf.html#multipleDatasources
    

    【讨论】:

    • 您好 Ernesto,我意识到我没有为我真正需要回答的问题添加足够的信息。我有多个数据源,直到在运行时看到数据我才会知道要使用哪个数据源。我相信我不能将多个数据源注入到服务中。所以更大的问题实际上是我如何选择我想去的数据库,使用 Sql 类并获得自动池。我可能想在服务课程之外的课程中这样做。我不需要服务事务管理。
    【解决方案2】:

    如果你像这样创建Sql 对象,我相信它会使用连接池

    class SomeSerive {
    
      SessionFactory sessionFactory
    
      def someMethod() {
        Sql sql = new Sql(sessionFactory.currentSession.connection())
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-22
      • 2014-11-04
      • 2014-07-11
      • 1970-01-01
      • 2011-02-17
      相关资源
      最近更新 更多