来自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),
)
'''
答案 0 :(得分:7)
如果您执行:
Sql.newInstance(...)
您将创建一个新连接,而您没有使用连接池。
如果要使用连接池,可以使用以下命令创建服务:
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
答案 1 :(得分:1)
如果您创建这样的Sql
对象,我相信它将使用连接池
class SomeSerive {
SessionFactory sessionFactory
def someMethod() {
Sql sql = new Sql(sessionFactory.currentSession.connection())
}
}