在Grails应用程序启动期间执行SQL插入

Mal*_*lla 5 grails datasource

我正处于开发阶段,尝试使用内存数据库并在Grails应用程序启动期间加载一些数据.我的问题是,有没有办法编写/配置可以在启动期间执行的SQL插入语句.

Bur*_*ith 9

您可以在BootStrap.groovy中执行此操作.如果为dataSourcebean 添加依赖注入,则可以将其与groovy.sql.Sql实例一起使用来执行插入:

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'])
   }
}
Run Code Online (Sandbox Code Playgroud)

您可能最好使用GORM,假设这些是使用域类管理的表.比如运行类似的东西new Book(author: 'me', title: 'some title').save()