7 Object Relational Mapping (GORM) - Reference Documentation
Authors: Graeme Rocher, Peter Ledbrook, Marc Palmer, Jeff Brown, Luke Daley, Burt Beckwith, Lari Hotari
Version: 3.2.0.RC1
7 Object Relational Mapping (GORM)
Domain classes are core to any business application. They hold state about business processes and hopefully also implement behavior. They are linked together through relationships; one-to-one, one-to-many, or many-to-many.GORM is Grails' object relational mapping (ORM) implementation. Under the hood it uses Hibernate 3 (a very popular and flexible open source ORM solution) and thanks to the dynamic nature of Groovy with its static and dynamic typing, along with the convention of Grails, there is far less configuration involved in creating Grails domain classes.You can also write Grails domain classes in Java. See the section on Hibernate Integration for how to write domain classes in Java but still use dynamic persistent methods. Below is a preview of GORM in action:def book = Book.findByTitle("Groovy in Action")book .addToAuthors(name:"Dierk Koenig") .addToAuthors(name:"Guillaume LaForge") .save()
7.1 Quick Start Guide
A domain class can be created with the create-domain-class command:grails create-domain-class helloworld.Person
If no package is specified with the create-domain-class script, Grails automatically uses the application name as the package name.This will create a class at the location
grails-app/domain/helloworld/Person.groovy such as the one below:package helloworldclass Person {
}
If you have the dbCreate property set to "update", "create" or "create-drop" on your DataSource, Grails will automatically generate/modify the database tables for you.
You can customize the class by adding properties:class Person {
String name
Integer age
Date lastVisit
}grails console
7.1.1 Basic CRUD
Try performing some basic CRUD (Create/Read/Update/Delete) operations.Create
To create a domain class use Map constructor to set its properties and call save:def p = new Person(name: "Fred", age: 40, lastVisit: new Date()) p.save()
Read
Grails transparently adds an implicitid property to your domain class which you can use for retrieval:def p = Person.get(1) assert 1 == p.id
Person object back from the database.
You can also load an object in a read-only state by using the read method:def p = Person.read(1)
def p = Person.load(1)
Update
To update an instance, change some properties and then call save again:def p = Person.get(1)
p.name = "Bob"
p.save()Delete
To delete an instance use the delete method:def p = Person.get(1) p.delete()
