在Grails应用程序启动过程中执行SQL插入 [英] Executing SQL inserts during Grails application startup
问题描述
我正处于开发阶段,尝试使用内存数据库并在Grails应用程序启动期间加载一些数据。我的问题是,是否有任何方法来编写/配置可以在启动过程中执行的SQL插入语句。
I am in development phase, trying to use in-memory DB and load it with some data during Grails application start up. My question is, is there any way to write/configure SQL insert statements that can be executed during startup.
推荐答案
您可以在BootStrap.groovy中执行此操作。如果为 dataSource
bean添加依赖项注入,则可以将它与 groovy.sql.Sql
实例一起使用插入:
You can do this in BootStrap.groovy. If you add a dependency injection for the dataSource
bean you can use it with a groovy.sql.Sql
instance to do inserts:
import groovy.sql.Sql
class BootStrap {
def dataSource
def init = { servletContext ->
def sql = new Sql(dataSource)
sql.executeUpdate(
'insert into some_table(foo, bar) values(?, ?)',
['x', 'y'])
}
}
尽管使用GORM,假设这些是使用域类管理的表。例如。运行类似于 new book(author:'me',title:'some title')。save()
You would probably be better off using GORM though, assuming these are tables that are managed with domain classes. E.g. run something like new Book(author: 'me', title: 'some title').save()
这篇关于在Grails应用程序启动过程中执行SQL插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!