Posts Tagged ‘h2’

The H2 Database Console in Grails 2

Posted in Code on November 15th, 2011 by ataylor284 – 1 Comment

The H2 Database Engine replaces HSQLDB as the default, embedded database engine in Grails 2.0. One of the great features it adds is a web-based console for browsing tables, checking the schema, executing SQL queries, and all the other stuff you’d use a database client for.

This was possible in older versions of grails but it comes ready to go out of the box in Grails 2. It’s mapped to http://localhost:8080/<app-name>/dbconsole.

Let’s create a quick grails app to see it in action:

$ grails create-app test-app
| Created Eclipse project files.
| Created Grails Application at ~/dev/test-app
$ cd test-app
$ grails
| Enter a script name to run. Use TAB for completion:
grails> run-app
| Server running. Browse to http://localhost:8080/test-app
| Application loaded in interactive mode. Type 'exit' to shutdown.
| Enter a script name to run. Use TAB for completion:

At this point, browse to http://localhost:8080/test-app/dbconsole. The default login parameters should match the defaults in grails-app/conf/DataSource.groovy, so pressing Connect should log us into the development database.

H2 Database Console Login Window

H2 Database Console Login Window

grails> create-domain-class test.Book
| Created file grails-app/domain/test/Book.groovy

Book.groovy will be an empty domain class, so open it up add a title property. Then hit refresh in the console, and now we see a BOOK table in the right sidebar. Let’s create a book instance with the grails shell:

grails> shell
| Packaging Grails application.....
Groovy Shell (1.8.3, JVM: 1.6.0_29)
Type 'help' or '\h' for help.
groovy:000> new test.Book(title: 'Grails in Action').save(failOnError: true)
===> test.Book : 1
groovy:000> exit

Now if we enter SELECT * FROM BOOK in the database console, our book will show up.

H2 Database Console

H2 Database Console