从以下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)
Run Code Online (Sandbox Code Playgroud)
或者如果您有现有连接(可能来自连接池)或数据源使用其中一个构造函数:
def sql = new Sql(datasource)
Run Code Online (Sandbox Code Playgroud)
现在你可以调用sql,例如创建一个表:
sql.execute '''
create table PROJECT (
id integer not null,
name varchar(50),
url varchar(100),
)
'''
Run Code Online (Sandbox Code Playgroud)
如果你执行:
Sql.newInstance(...)
Run Code Online (Sandbox Code Playgroud)
您将创建一个新连接,而您没有使用连接池.
如果要使用连接池,可以使用以下命令创建服务:
grails create-service org.foo.MyService
Run Code Online (Sandbox Code Playgroud)
然后,在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
}
}
Run Code Online (Sandbox Code Playgroud)
有关详细信息,请参阅:http://grails.org/doc/2.0.x/guide/services.html
编辑:
要管理多个数据源,您可以根据Grails版本执行以下操作之一.
如果您使用的Grails版本大于1.1.1(而不是2.x),则可以使用以下插件:
http://grails.org/plugin/datasources
Run Code Online (Sandbox Code Playgroud)
如果您使用的是Grails 2.x,您可以使用开箱即用的支持:
http://grails.org/doc/2.0.0.RC1/guide/conf.html#multipleDatasources
Run Code Online (Sandbox Code Playgroud)