1

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.

tim_yates
  • 167,322
  • 27
  • 342
  • 338
Rafiq Flucas
  • 111
  • 1
  • 8

3 Answers3

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.

Community
  • 1
  • 1
erturne
  • 1,799
  • 1
  • 15
  • 29
  • 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

Two ways:

  • GORM
  • raw JDBC (via spring's JdbcTemplate)
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • 3
    Not 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
    But why then bother with grails? – tim_yates Oct 31 '11 at 22:28
  • 2
    I 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
  • 1
    stepping 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