Grails: Use run-script to ppopulate a H2 database

792 views Asked by At

I have got some problem to populate my H2 datatase via the run-script command:

Here is my domain class:

class Lab {

String name

static constraints = {
}

String toString() {
    return name
}

static mapping = {
    sort "name"
}

}

I generated the controller and view using the grails generate-all command.

I wrote a simple groovy script to add new Lab:

import groovy.sql.Sql

def grailsApplication
def dataSource = ctx.getBean("dataSource")
def sql = new Sql(dataSource)

Lab a = new Lab(name: "AAAAAAAAAAAAAA")
assert a.save(flush: true)

if (!a.hasErrors()) {
  println "${a.name} saved successfully!"
}

Now, when I run it, everything looks to work fine:

AAAAAAAAAAAAAA saved successfully!
| Script scripts/createLab.groovy complete!

But when I refresh the webpage page http://localhost:8080/myapp/lab/index, I cannot see any new Lab created.

I am using the default H2 database setting.

Did I missed something?

1

There are 1 answers

4
leomeurer On

You are using a h2 memory db called devDB (h2:mem:devDb;).

I see two options here. If you like to have a physical file to represent your db you can use file instead mem.

h2:file:devDb;

Or you can put your scripts insite Bootstrap.groovy, and every time you start your application these records will be generated.

This way:

Lab.findOrSaveWhere(name:'AAAAAAAAAA')