About Nitin Kumar

Nitin Kumar works as a Solution Architecture in Wipro Technologies specialize in SOA. He has over twelve years of experience in information technology architecting and developing software systems, focus mainly on JEE solutions.

Grails – GORM Tutorial

Grails is known as domain driven language that means we can build application using bottom to top approach which is more nearer to object oriented programming. GORM (Grail Object Relational Mapping) uses intern Hibernate to map the domain with table which gives life to Domain modeling. If we combined everything just only based on domain we could build the whole web application. Scaffolding can bring domain design directly to visible state to business users with extra involvement
grails-gorm
But keep in mind Grails is an agile development framework. That means we build application quickly, deploy and run in one shot and make changes any layer without impacting other parts such UI, domain modeling, service class etc.

Create Domain class

Grails treats the domain classes as the most important part of the application.  This is root of application which helps to visualizes overall application. You could treat it as an entity object which tightly coupled with database table.

Let’s start with creating a simple domain class name User with fields’ username and userpassword

D:\grails_book\firstapp>grails create-domain-class com.UserManagement.User
This creates a new class file in /firstapp /domain/com/UserManagement/User.groovy
(A corresponding unit test in /test/unit/com/grailsinaction/UserTests.groovy).
package firstapp.domain.com.UserManagement
class User {
 long userid
 String username
 String password
 static constraints = {
 username(blank: false)
 }
}

Note: We no need to worry about setter and getter as Grails/Groovy dynamically generate.

By default, all the fields in a domain class are persisted to the database. The User class contains two fields’ username and password which will map to table User with column name username and password. GORM provide following dynamic methods to access database without exploring the PL/SQL directly.

  • User.save() saves the data to the User table in the database.
  • User.delete() deletes the data from the User table.
  • User.list() returns a list of Users.
  • User.get() returns a single User

Relationship

Grails gives flexibility to make various combination of mapping such as one-to-one, one-to-many, many –to-many.

It uses belongsTo for unidirectional and hasMany and direct reference for bidirectional. hasMany also uses for many relationship. In subsequent topic we will discuss in detail uses of these properties.

One-to-one relationships

One-to-one relationships could be unidirectional or bidirectional with single valued reference. For example User has single address and each address belongs to only one user. Following figure illustrates that a one-to-one relationship between user and his address.

Figure Assigning one-to-one on entities
one-one
For defining relationship between user and address first we will create domain class as follows

We will start creating

D:\grails_book\firstapp>grails create-domain-class com.onetoone.domain.Book
D:\grails_book\firstapp>grails create-domain-class com.onetoone.domain.Author

In below example belongsTo field inform GORM that Book has a relationship to Author and eligible for cascade, so if any Author deleted, the matching Book will also be deleted. We can define One-to-one relationship unidirectional or bidirectional by defining belongsTo on Address object and adding Address reference on User (owner) object.

package com.onetoone.domain
class Book {
 Long id
 String bookName
 String bookDesc
 static belongsTo=Author //Book belong to Author

static constraints = {
 //For validtion
 }

String toString(){
 "Book name:${bookName}"
 }
}

One-to-many Relationship

One-to-many relationship occurs when one object has a multivalued relationship with another object.

For example one-to-many relationship exists between employee and department. Below figure depicts that a department can have many employees, but that each individual employee can work for only one department

Figure : Assigning one-to-many on entities
one-many
Grails introduces hasMany and belongsTo properties to establish one-to-many relationship.

For e.g. hasMany need to define on Department domain and belongsTo need to define on Employee domain class as follows:

package com.onetomany.domain

class Department {
 long id
 String departname
 String departmentLOB
 static hasMany=[employees:Employee]
static constraints = {
 }
}

package com.onetomany.domain

class Employee {
 long id
 String employeename
 String emailid
 String phone
static belongsTo=Department
static constraints = {
 employeename(blank: false)
 }
 static mapping = {
 sort employeename:"desc"// "desc" for descending
 // "asc" for ascending
 }
}

After establishing one-to-many relationship between Department and Employee, Grails automatically adds two new methods to your User class: Department.addToEmployees () and Department.removeFromEmployees () to add the reference objects.

Please click here to download the code

Conclusion

Domain is the heart of Grail based development which map domain as entity to database table without configuration or annotation (used on JPA based framework).

 

Reference: Grails – GORM Tutorial from our JCG partner Nitin Kumar at the Tech My Talk blog.
Related Whitepaper:

Java Essential Training

Author David Gassner explores Java SE (Standard Edition), the language used to build mobile apps for Android devices, enterprise server applications, and more!

The course demonstrates how to install both Java and the Eclipse IDE and dives into the particulars of programming. The course also explains the fundamentals of Java, from creating simple variables, assigning values, and declaring methods to working with strings, arrays, and subclasses; reading and writing to text files; and implementing object oriented programming concepts. Exercise files are included with the course.

Get it Now!  

Leave a Reply


+ one = 10



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books
Get tutored by the Geeks! JCG Academy is a fact... Join Now
Hello. Add your message here.