blog rss feed

A guide to mapping databases in Grails with GORM

Keywords:

Last editor: Dave Cherry, last modified: Aug 3, 2008

Creating a new domain object

In order to create a new record in the database, we must first create an instance of the object that will represent it. This instance is considered to be transient because it has not yet been saved. Notice that I use named parameters on construction to fill in all the properties. Also of note, I cannot pass in a transient category because Book is not the owner of Category. Finally, To save the instance, just call save. See the example:

def cat = Category.get(1)
def book = new Book(title:'New Book', description:'A new book by Dave',
reference:
'someref', revision:1, category: cat)
book.save()

Modifying an existing object

In order to modify an existing domain object, one simply calls save() save on the instance. See the example below.

def book = Book.get(1)
// modify book
book.save()

Removing an existing object

Remove and object from the database simply by calling the delete method on the domain object.

def book = Book.get(1)
book.delete()

Adding an item to a one-to-many relation

We can add an item to a one-to-many relation by calling the method addTo<property> on the domain object. If the child object belongsTo the parent, then transient instances of the child will be saved by the framework. See the example below:

def book = book.get(1);
book.addToReviews(
new Review(author:'dave', reviewText:'great'))
book.save()

Populating the database during initialisation

During initialisation the Bootstrap object's init method is called. This method provides us with a way to pre-populate the database. In the example below we create a category, then create a book within that category, and lastly create a review for the book. Bootstrap can be found in the grails-app/conf directory.

class BootStrap {

def init = { servletContext ->
Category c =
new Category(name: 'Grails')
c.save()

Book b =
new Book(title: 'Grails', description:'grails',
reference:
'gr123456789', revision:1,
category: c)

Review r =
new Review(author: 'dave', reviewText: 'Great')
b.addToReviews(r)
b.save()
}

def destroy = {
}
}
<< 1 2 3 4 5 >>

Please leave a comment



Search

Blog calendar

blog: previous month September 2010 blog: next month
su mo tu we th fr sa
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30