Last editor: Dave Cherry, last modified: Aug 3, 2008
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()
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()
Remove and object from the database simply by calling the delete method on the domain object.
def book = Book.get(1)
book.delete()
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()
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 = {
}
}