Connecting MySql to Grails

By default, Grails applications are configured to use an in-memory HSQLDB database.

Steps to connect to MySql database:

1. Create database to be used.

create database database_name

2. Create your application.

grails create-app app_name

3. After creating app, go to BuildConfig.groovy file and add following:

     dependencies {

         runtime ‘mysql:mysql-connector-java:5.1.24′

}

Uncomment maven repository if it is commented.

4. Now update datasource.groovy file.

 dataSource {
   pooled = true
driverClassName = “com.mysql.jdbc.Driver”
dialect = “org.hibernate.dialect.MySQL5InnoDBDialect”
//logSql=true
}

5. For environment specific settings:

      environments {
                     development {
                                  dataSource {
                                            dbCreate = “update” // one of ‘create’, ‘create-drop’, ‘update’, ‘validate’, ”
                                            url = “jdbc:mysql://localhost/database_name?                     useUnicode=yes&characterEncoding=UTF-8&autoReconnect=true”
                                            username = “XXX”
                                            password = “XXX”
                                                   }
                      }
test {
                     dataSource {
                               dbCreate = “update”
                                url = “jdbc:mysql://localhost/database_name?useUnicode=yes&characterEncoding=UTF-8&autoReconnect=true”
                               username = “XXX”
                               password = “XXX”
                      }
}
production {
                    dataSource {
                               dbCreate = “update”
                               url = “jdbc:mysql://localhost/database_name?useUnicode=yes&characterEncoding=UTF-8&autoReconnect=true”
                              username = “XXX”
                              password = “XXX”
                              pooled = true

                            }
             }
      }
}

 


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

 

 

How Grails MVC works?

Grails is an MVC platform that’s used for developing MVC applications.

The architecture and different components used in the Grails MVC application is shown as below:

Grails MVC Architecure

 

It shows the request flow on a Grails MVC application.

  • Model:

Model is a Java object which stores the data that can be used by       the controllers and views. Grails provides you a binded mechanism that help you references your model from the grails UI components like g:each.

Grails provides an inline validation in the model. Grails domain class can express domain constraints simply by defining a public static property constraints that has a closure as a value.

  • Controller:

It is a servlet which handles all the request from the front end. In general, Grails servlet extends Spring’s DispatcherServlet to bootstrap the Grails environment (SimpleGrailsController) for handling the requests. SimpleGrailsController delegates to a class called SimpleGrailsControllerHelper that actually handles the request.

A proper name for your controller must be ended with the controller phrase, that would help Grails to discover the controllers conventionally.

  • View:

Groovy server pages is responsible for rendering the models. Grails uses GroovyPagesTemplateEngine for rendering of GSP views as those views support the concept of custom tag libraries. You can access the g tags directly within your GSP without any need of importing it. A lot of ready-made tags are provided for your use. Grails g library provides you ability of accessing data binded and domain class associations.


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

 

 

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.

 

 

Data-binding in AngularJs

There are two types of data-binding in AngularJs:

1. One-Way Binding/ Basic Data-Binding

2. Two-way Binding

One-Way Binding:

A data binding can be specified in two different ways:

  • with curly braces: {{expression}}
  • with the ng-bind directive: ng-bind=“varName”

Example to show one-way binding:

HTML page(View):

<!DOCTYPE html>
<html>
<head>
<script src=”angular.js”></script>
</head>

<body ng-app ng-init=”firstName = ‘Daniel'; lastName = ‘Smith';”>
<strong>First name:</strong> {{firstName}}<br />
<strong>Last name:</strong> <span ng-bind=”lastName”></span>
</body>
</html>

We’re saying one way data binding because the model values (here the variables represent the model) are automatically assigned to the HTML placeholder elements specified through the data binding notation, but the HTML elements don’t change the values in the model (one way).

Two-way data binding:

We have a two way data binding when a model variable is bound to a HTML element that can both change and display the value of the variable. In general, we could have more than one HTML element bound to the same variable. We use the ng-model directive to bind a model variable to the HTML element that can not only display its value, but also change it.

<!DOCTYPE html>
<html>
<head>
<script src=”angular.js”></script>
</head>

<body ng-app ng-init=”firstName = ‘Daniel'; lastName = ‘Smith';”>
<strong>First name:</strong> {{firstName}}<br />
<strong>Last name:</strong> <span ng-bind=”lastName”></span><br />
<br />
<label>Set the first name: <input type=”text” ng-model=”firstName”/></label><br />
<label>Set the last name: <input type=”text” ng-model=”lastName”/></label>
</body>
</html>

In the example, we bind the firstName and lastName model variables to a couple of HTML input elements. When the page is loaded, the value of the input elements are initialized to those of the respective model variables and whenever the user types something in an input, the value of the model variable is modified as well (two way).


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

 

 

How to redirect to home route when no route is defined?

In AngularJs, $routeProvider is used for configuring routes.

Requires the ngRoute module to be installed.

when(path, route);

Adds a new route definition to the $route service.

$routeProvider.when(‘/index’, { templateUrl: ‘/view/project.html’, controller: ‘projectController’ });

You can use,

otherwise(params)

Sets route definition that will be used on route change when no other route definition is matched.

.otherwise({ redirectTo: ‘/Home’ });

To redirect to home page when no other route is provided.


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

 

 

 

Dynamic URL’s in angularJs

Dynamic URL’s in AngularJs:

To have dynamic URL’s in AngularJs you need to include             angular-route.js.

Then, you can use following code snippet to dynamically redirect URLs:

angular.module(‘myapp’,[]).
config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/', { templateUrl: '/menu/Noodle.html', controller: HomeController });
$routeProvider.when('/about', { templateUrl: '/pages/about.html', controller: AboutController });
$routeProvider.when('/privacy', { templateUrl: '/pages/privacy.html', controller: AboutController });
$routeProvider.when('/terms', { templateUrl: '/pages/terms.html', controller: AboutController });
$routeProvider.otherwise({ redirectTo: '/' });
}]);

You can change URLs according to your requirements.


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

 

AngularJs Routes

AngularJS routes enable you to create different URLs for different content in your application. A route is specified in the URL after the # sign.

As shown below:

http://angularjsapp.com/index.html#users

When browser loads application it bydefault goes to index.html but angularJs looks at routes and decides which template to show.

Routing in AngularJs:

1. Include AngularJs Route Module:

We need to include AngularJs Route Module if routing is to be done.

<script src=”https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular-route.min.js”></script>

2. Declare dependency on Route Module:

Application needs to declare dependency on route module in order to use ngRoute module.

var module = angular.module(“sampleApp”, ['ngRoute']);

3.  ngView Directive:

Use ngView inside <div>, so that template specific to route will be displayed here.

<div ng-view></div>

4. Configure $routeProvider:

The $routeProvider is what creates the $route service. By configuring the$routeProvider before the $route service is created we can set what routes should result in what HTML templates being displayed. As shown below:

module.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/route1', {
templateUrl: 'template-1.jsp',
controller: 'UserController'
}).
otherwise({
redirectTo: '/'
});
}]);

The when() function takes a route path and a JavaScript object as parameters.

The otherwise() function takes a JavaScript object. It tells AngularJS what it should do if no route paths matches the given URL.

5. Provide Links to Routes:

Provide links to route as shown below :

<a href=”#/route1“>Route 1</a><br/>

6. Route paramenters:

We can provide parameters with routes path as shown:

#/users/1

Here, ‘1’ is the parameter passed with route path.

We can read parameters while configuring $routeProvider as shown below:

when(‘/route1/:param‘, {
templateUrl: ‘template-1.jsp’,
controller: ‘RouteController’
})

Controller can get access to params using $routeParams service as shown below:

module.controller(“UserController”, function($scope, $routeParams) {
$scope.param = $routeParams.param;
})

Now, your view can also get access to param as $scope.param is assigned the value of $routeParams.param.


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

 

 

 

 

Dependency injection in AngularJs

 

AngularJs comes with built-in dependecy-injection mechanism. You can divide your application into multiple different types of components which AngularJS can inject into each other.

Injecting a value :

Injecting a value into an AngularJS controller function is done simply by adding a parameter with the same name as the value (the first parameter passed to the value() function when the value is defined). Here is an example:

var myModule = angular.module(“myModule”, []);

myModule.value(“numberValue”, 999);

myModule.controller(“MyController”, function($scope, numberValue) {

console.log(numberValue);

});

Injecting value into a Factory:

Factory is a function that creates values. Once created, the value is reused for all services, controllers etc. which need it injected.

You can inject a value into a factory. It works just like when a value is injected into a controller. Here is an example:

var myModule = angular.module(“myModule”, []);

myModule.value(“numberValue”, 999);

myModule.factory(“myFactory”, function(numberValue) {
return “a value: ” + numberValue;
});

Injecting values in a Service:

A service in AngularJS is a singleton JavaScript object which contains a set of functions. The functions contain whatever logic is necessary for the service to carry out its work.

You can inject values into a service, just like you can inject values into controllers, or services into controllers etc. Here is an example:

var myModule = angular.module(“myModule”, []);

myModule.value (“myValue” , “12345”);

function MyService(myValue) {
this.doIt = function() {
console.log(“done: ” + myValue;
}
}

myModule.service(“myService”, MyService);

Provider:

Providers in AngularJS is the most flexible form of factory you can create. You register a provider with a module just like you do with a service or factory, except you use the provider() function instead. Here is an AngularJS provider example:

var myModule = angular.module(“myModule”, []);

myModule.provider(“mySecondService”, function() {
var provider = {};

provider.$get = function() {
var service = {};

service.doService = function() {
console.log(“mySecondService: Service Done!”);
}

return service;
}

return provider;
});

Injecting provider into controller:

myModule.controller(“MyController”, function($scope, mySecondService) {

$scope.whenButtonClicked = function() {
mySecondService.doIt();
}

});

Injecting Constants:

Constants in AngularJS are defined using the module.constants() function.As shown below:

myModule.constant(“configValue”, “constant config value”);

Example as shown below:

   myservices.config( function( mySecondServiceProvider, configValue ) {
mySecondServiceProvider.doConfig(configValue);
});

Dependencies Between Modules:

It is possible for one module to use the values, factories and services of another module. In order to do so, a module needs to declare a dependency on the module which contains the values, factories and services it wants to use. Example as shown below:

var utilModule1 = angular.module(“utilModule1 “, []);
utilModule1 .value (“myValue” , “12345”);
var utilModule2= angular.module(“utilModule2″, ['utilModule1']);
utilModule2.controller(“MyController”, function($scope, myValue) {
}

Here, second module utilModule2 want to use values, factories and services of first module utilModule1. So, it will have to show dependency on utilModule1.

 


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