Sunday, March 16, 2008

Data operator CRUD in Grails

How to implement CRUD(create,read,update,delete) in Grails.The answer is ,it's simple.Because of the Grails's GROM is based on Hibernate and we have already have the Domain class,and it's alsp maped to database table.So now,you can just simple use save(),update(),delete() method.let me demonstrate how to do these:In this section,I will use the Project and Issue Domain Object in Sparrow.
/**Create data*/
//create a project
def project1=new Project(title:'Project1',description:'Hello world!',createDate:new Date())
//now we have the project object.we will save it.
project1.save()
//as you can see ,we never define the method save().but we can use it,because Grails auto //generate it in runtime for us.when we call this method,the project information will be saved in database table,it's cool.
//Now we'll define issue object
def issue1=new Issue(summary:'Issue1',description:'This is a issue',createDate:new Date(),project:project1)
//we created the issue object,but the different in this place.we have a parameter project:project1 ,because the project and issue has a one-many relationship,so we need point there whcih Project that this Issue belong to.
/**read*/
after we create the object information.we usually need get these data.how to do that?the answer is get(id) and exists(id) method.
//get Project by ID
def p1=Project.get(1)//we will use id parameter get a project,which id is 1
def boolean=Project.exist(1)//the exists method will return ture if it's exists.
The exists method, reads better and is arguably more performant than get method.
if(Project.get(1)){
def p=Project.get(1) //bad performant,because you called twice get method
}
if(Project.exists(1)){
def p=Project.get(1) //better performant
}
/**update Object*/
//update object is easy
def p=Project.get(1)
p.title='New title'
p.save()

/**delete Object*/
def p=Project.get(1)

p.delete()

/**sort,listing,and counting*/

GORM provides a list method, which takes a number of named arguments such as max, offset,
sort, and order to customize the results, the definitions of which are listed here:
• max: The maximum number of instances to return
• offset: The offset relative to 0 of the first result to return
• sort: The property name to sort by
• order: The order of the results, either asc or desc for ascending and descending order respectively

//demonstrate
//get all objecta
def allProject=Project.list()
//get top 10 objects
def topten=Project.list(max:10)
//sort objects
def sortingProject=Project.list(max:10,sort:'createDate')
//sort and order
def sortingProject2=Project.list(max:10,sort:'createDate',order:'desc')
//order by column name
def allBycreateDate=Project.listOrderByCreateDate()
Note:the listByCreateDate is auto generate by Grails.it's a role,that means listOrderBy+property'name

No comments: