I was wondering how to persist data to a hsqldb. For example I am trying to save a simple name to a database but I cant seem to figure out how to persist it.
Asked
Active
Viewed 1,127 times
3 Answers
5
The recommended approach is to create a domain class with a String name property. Then you can save it, and you're done. First, create the domain class:
$ grails create-domain-class com.foo.Person
Then edit the grails-app/domain/com/foo/Person.groovy:
package com.foo
class Person {
String name
}
In controller actions or service methods you can create, save, and retrieve data:
def heMan = new Person(name: 'He Man')
if ( !heMan.save() ) {
// Handle problems saving (e.g. constraint violations)
}
def h = Person.findByName('He Man')
println h.name
An alternative approach is to work with JDBC directly. You can have dataSource bean automatically injected into your controller, then use the groovy.sql.Sql class to query that dataSource. Check out this stackoverflow.com question.
-
Thanks alot. Also I have another question, Say for instance I wanted to save data from a field in one of my gsp pages into its respective location in a hsql database. Do you have any suggestion on how I should try this? – Rafiq Flucas Nov 01 '11 at 23:04
2
-
3Not that hard, kind of baked in to the framework--as long as you're working with a Grails model, pretty trivial, no? – Dave Newton Oct 31 '11 at 22:23
-
well, it's trivial for me and you, but it might not be that for beginners. Comparatively, I think it's "harder" than the JDBC thing, because it adds the ORM concept, with which you may not be familiar – Bozho Oct 31 '11 at 22:25
-
2
-
2I think if you're using Grails it's way easier to do it the Grails way since you don't really have to *do* anything, and what you *do* need to do is documented. Stepping outside the framework adds a layer of complexity. OTOH, if something Grails-y *breaks*, then not knowing the underlying frameworks is a serious liability. – Dave Newton Oct 31 '11 at 22:32
-
@DaveNewton +1 If you are going to use JDBC, you may as well Groovy by itself – tegbains Oct 31 '11 at 22:38
-
1stepping outside of the framework has given me lots of headaches :) but using a JdbcTemplate isn't such a thing. But I'll reverse the order of the bullets, I agree that gorm is top priority. – Bozho Oct 31 '11 at 22:38
1
I would suggest starting with a good Grails tutorial such as this one at IBM or one of these. Learn to use GORM. It will make your life better.

tegbains
- 597
- 3
- 14