Category Archives: Grails

What is GORM ?

GORM is Grails’ object relational mapping (ORM) implementation, which sits on top of the very popular Hibernate framework. If you are familliar with Hibernate then understanding GORM will be easy. GORM is very straightForward and easy to learn.

ORM frameworks objective is to present an API where you can just think and program in objects, and the underlying framework will handle how to interface with the relational database.
Configuration:
Grails have by default database configuration already so that you could start coding your business logic right away. By default, it uses embedded H2 database. You can change this configuration if you want in Datasource.groovy file, as shown below:
dataSource {
pooled = true
driverClassName = “com.mysql.jdbc.Driver”
dialect = “org.hibernate.dialect.MySQL5InnoDBDialect”
}

As GORM is ORM so corresponding table will be created automatically for all your domain classes. You don’t have to create the tables manually in your database or write an sql statement for this.

When tables are created you can start with CRUD part.

Lets take an example of Project class:
class Project{
String name;

}

Create operation:
Project p = new Project()
p.name = “Project_1″
p.save()

or you can do as following also:
Project p = new Project(name:”Project_1″).save()

Read operation:
Following code retrieves row of table Project with id=’12’.
Project p = Project.get(12);

Update operation:
To perform update operation you can do following :
Project p = Project.get(12)
p.name = “Project_New”
p.save()

Delete operation:
To delete a row just invoke delete() on instance to delete as shown below:
Project p = Project.get(12)
p.delete()

With GORM writing of business logic becomes very easy and convenient .


ProsperaSoft offers Grails development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft Grails experts and consultants.

How to perform Join operation with one-to-many relationship in Grails?

Joins are very important when you need to retrieve data from two or more tables based on some condition. In Grails, you can use HQL queries to perform join operations. We have executeQuery to perform joins in grails.

Lets take an example to show how joins can be performed with One-to-Many relationship:

Suppose there are classes Project and Task.

class Project {
     static hasMany = [tasks:Task]
     String name
}

class Task{
        static belongsTo = Project 
       Project project
       String name
}

Assume we have inserted following data:

class BootStrap {
def init = { servletContext ->
if ( Project .count() == 0 ) {
Project prj_1= new Project (name:’Project_1′).save()
new Task(project:prj_1, name:’Task_1′).save()
new Task(project:prj_1, name:’Task_2′).save()
Project prj_2= new Project (name:’Project_2′).save()
new Task(project:prj_2, name:’Task_3′).save()
new Task (project:prj_2, name:’Task_4′).save()
Project prj_3 = new Project (name:’Project_3′).save()
new Task(project:prj_3 , name:’Task_5′).save()
new Task(project:prj_3 , name:’Task_6′).save()
}
}
def destroy = {
}
}

Here, are some problems where we need to retrieve data from both tables and we are going to use joins:

Problem 1. Which Project does Task Task_3 belong?

def result = Project.executeQuery(
“select p from Project p join p.tasks pt where pt.name = ‘Task_3′”)
result.each { project ->
println “Project is ${project.name}”
}

Output will be “Project is Project_1″

Problem 2. How many tasks does Project_3 have?

def result = Project.executeQuery(
“select count(*) from Project p join p.tasks pt where p.name = ‘Project_3′”)
println “${result[0]}”

Output will be “2” as we have 2 tasks for Project_3.

Problem 3. How many tasks does each project have?

def result = Project.executeQuery(
“select p.name, count(*) from Project p join p.tasks pt group by p”)
result.each { item ->
println “Project ${item[0]} has ${item[1]} tasks”
}

Output will be as shown below:

Project  Project_1 has 2 tasks
Project  Project_2 has 2 tasks
Project  Project_3 has 2 tasks

We can perform Join without having any relationship between tables.


ProsperaSoft offers Grails development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft Grails experts and consultants.

 

 

 

How to save list of JSON objects to Grails domain and render it?

To get JSON from request(POST) do following:

Request-type: POST

Request_data(JSON):[{

name : "TestName"

surname: "TestSurname"

}]

We can post JSON data from Postman REST client.

Domain:

class person{

String name;

String surname;

}

Controller:

import grails.converters.deep.JSON
import groovy.json.JsonSlurper

class PersonController{

def saveJsonToDomain(){

String jsonObject = request.getJSON();                                                                      // get JSON data from request body
println “jsonObject : ” + jsonObject;
def jsonList = new JsonSlurper().parseText(jsonObject);
println “jsonList.size() : ” + jsonList.size();
for(jsonObj in jsonList){
try{
Person person = new Person(jsonObj);
person.save(flush:true); // save JSON directly to grails domain
render person as JSON // render JSON object
}
catch(Exception e){
e.printStackTrace();
render “Error saving category : ” + e;
}
}

}

}

Don’t forget add the json data with same name as variable names in domain.


ProsperaSoft offers Grails development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft Grails experts and consultants.

 

 

How to configure Spring security in Grails

Following are the steps to configure spring security in grails:

1. Create project using  command grails create-app projectName.

2.  Configure Spring security core

First of all, we have to install Spring Security Core plugin into our project. Edit  BuildConfig.groovy and modify the plugins section as below:

plugins {

// plugins for the build system only
build “:tomcat:7.0.42″

// plugins for the compile step
compile “:scaffolding:2.0.0″
compile ‘:cache:1.1.1′

// plugins needed at runtime but not for compilation
runtime “:hibernate:3.6.10.1″ // or “:hibernate4:4.1.11.1″
runtime “:database-migration:1.3.5″
runtime “:jquery:1.10.2″ // <– If using 1.8.3, update to this version
runtime “:resources:1.2″

compile ‘:spring-security-core:2.0-RC2′ //Added

}

Then run (optionally grails cleangrails compile while in project’s directory to have the plugin installed.

3. Let Spring Security Core plugin to create required  models and controllers for us. For that we have to run command

s2-quickstart 

This will create 3 domain classes User, Role and UserRole.

And also in controller it will create 2 controllers LoginController and LogoutController which along with views/login/auth.gsp and views/login/denied.gsp.

4. Add the end of Config.groovy file you can see these lines added by spring security plugin

// Added by the Spring Security Core plugin:
grails.plugin.springsecurity.userLookup.userDomainClassName =      ‘com.team.model.User’
grails.plugin.springsecurity.userLookup.authorityJoinClassName       = ‘com.team.model.UserRole’
grails.plugin.springsecurity.authority.className =     ‘com.team.model.Role’

5. At this step, Spring Security Core is configured properly.

Edit  BootStrap.groovy to tell Grails about our sample    users/roles.

import com.team.model.Role
import com.team.model.User
import com.team.model.UserRole

class BootStrap {

def init = { servletContext ->
def adminRole = new Role(authority: ‘ROLE_ADMIN’).save(flush: true)
def userRole = new Role(authority: ‘ROLE_USER’).save(flush: true)

def testUser = new User(username: ‘admin’, enabled: true, password: ‘admin’)
testUser.save(flush: true)

UserRole.create testUser, adminRole, true

assert User.count() == 1
assert Role.count() == 2
assert UserRole.count() == 1
}

def destroy = {
}
}

6. Now you can use @Secured to to secure access to methods of controller based on roles. For example,

@Secured(['ROLE_ADMIN'])

def index(){

render ‘Some sensitive data’

}

 


ProsperaSoft offers Grails development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft Grails experts and consultants.