Reputation: 335
I am developing a small grails application from a book and one of the steps it needs is to feed the database with initial data. When I do so using the GroovyConsole
, the script executes but doesnt persist the data.
DataSource.groovy
environment settings are as follows
development {
dataSource {
dbCreate = "update" // one of 'create', 'create-drop', 'update', 'validate', ''
url = "jdbc:h2:devDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE"
}
}
When I run the script in console, result
returns NULL
. I have been using GGTS for the application but I have no idea how to persist initial data from GGTS so I ran the grails console
command from the command prompt for this. Is this the right way? Is there a way to do it directly from GGTS?
PS: I have seen this question Seed data for grails application but it seems to be too advanced for where I am now and what I need.
Thanks
Upvotes: 2
Views: 1665
Reputation: 1
You can just add code in BootStrap.groovy under
{project}/grails-app/init/{project}/BootStrap.groovy
For example:
class BootStrap {
def init = { servletContext ->
// create a driver a save it in db
def user = new User(name: "juan")
driver.save()
}
def destroy = {
}
}
Upvotes: 0
Reputation: 42184
I would suggest you quite different approach. Create a service called e.g. BootstrapInitialDataService with one method called initData(). It's a good practice to extract an interface from that class (let's call it InitialDataService) so you can easily define different component bean for your development and production environments. In this initData() method you can simply create all your domain objects, but remember to check first if they already exist in the database. When you do this, inject this service in Bootstrap.groovy and run initData() in the bootstrap's init closure:
class Bootstrap {
def initialDataService
def init = {
initialDataService.initData()
}
In the resources.groovy file you can explicitly define your initialDataService bean:
beans = {
//.... other beans definition goes here
initialDataService(your.package.BootstrapInitialDataService)
}
Thanks that when you decide to change your init data bootstrap logic you would simply define a new bean and replace the definition in the resources.groovy - the rest stays the same. You can even use an environment switch to inject different beans in different environments - that's very powerful advantage.
Upvotes: 3
Reputation: 20699
prepare a SQL file with the insert
-statements you need and run it in the BootStrap.groovy
:
class BootStrap {
def dataSource
def init = { servletContext ->
Sql sql = new Sql( dataSource )
new File( pathToSql ).eachLine{ sql.executeInsert it }
sql.commit()
sql.close()
}
}
is simple enough, isn't it?
Upvotes: 3