Monday, 17 September 2012


HI THIS TOUTORIAL WILL HELP FULL FOR STARTUP IN GRAILS CREATED BY NAVEENRAJU
Parts

Part4: creating connection to mysql5.5 data base and opp

Saving data in to mysql and data base operations

1.By Default data is storing on h2 Database how

Step1: grails create-app MysqlDemo

Step2:grails create-domain-class Mysql

Step3:Code like this in folloing path

   C:/MysqlDemo/grails-app/domain/mysqlDemo/Mysql.groovy
package mysqldemo
class Mysql {
String name
String age
String country
static constraints = {
    }
}

Step4: grails create-controller Mysql

Step5:go to folloing path and code like this

            C:/MysqlDemo/grails-app/controller/mysqlDemo/MysqlController.groovy
package mysqldemo
class MysqlController {
static scaffold=Mysql
}



Step6:  Open following paths then u can see code like this

              C:/MysqlDemo/grails-app/conf/DataSource.groovy
              dataSource {
    pooled = true
    driverClassName = "org.h2.Driver"
    username = "sa"
    password = ""
}
hibernate {
    cache.use_second_level_cache = true
    cache.use_query_cache = false
    cache.region.factory_class = 'net.sf.ehcache.hibernate.EhCacheRegionFactory'
}
// environment specific settings
environments {
    development {
        dataSource {
            dbCreate = "create-drop" // one of 'create', 'create-drop', 'update', 'validate', ''
            url = "jdbc:h2:mem:devDb;MVCC=TRUE;LOCK_TIMEOUT=10000"
        }
    }
    test {
        dataSource {
            dbCreate = "update"
            url = "jdbc:h2:mem:testDb;MVCC=TRUE;LOCK_TIMEOUT=10000"
        }
    }
    production {
        dataSource {
            dbCreate = "update"
            url = "jdbc:h2:prodDb;MVCC=TRUE;LOCK_TIMEOUT=10000"
            pooled = true
            properties {
               maxActive = -1
               minEvictableIdleTimeMillis=1800000
               timeBetweenEvictionRunsMillis=1800000
               numTestsPerEvictionRun=3
               testOnBorrow=true
               testWhileIdle=true
               testOnReturn=true
               validationQuery="SELECT 1"
            }
        }
    }
}

Step6:  grails run-app

             Know browse with that server generated ip address
             u can fill the form all the information is stored in
             h2 database

Note: From  above  code   
    1)        
    pooled = true
    driverClassName = "org.h2.Driver"<---------------------- DriverClass
    username = "sa"<------------------------------------------------H2Database UserName
    password = ""<---------------------------------------------------H2Database Password
2)

environments {
    development {<--------------------------------For Development Environment
        dataSource {<--------------------------------DateSourceConfiguring
            dbCreate = " create-drop " // one of 'create', 'create-drop', 'update', 'validate', ''


create-drop:
for every  time u are running ur application it will create db while server off it will Drop the database tables


Update: If u want to fix the table in db permanently use "Update" For every updating Of server it won't need to create db tables just it will update rows and columns what u entered .Previous data will be on database as usual



           url = "jdbc:h2:mem:devDb;MVCC=TRUE;LOCK_TIMEOUT=10000"
jdbc:h2--------------------------------->In H2 DB
devDb --------------------------------->DataBaseSchemaName




2)Same program i am going to store values in Mysl how


Step1:Open folloing path and recode like this

        C:/MysqlDemo/grails-app/conf/DataSource.groovy
    
dataSource {
    pooled = true
    driverClassName = "com.mysql.jdbc.Driver"//<-------------------Sql Deiver Class
    username = "root"//<------------------------Sql User Name
    password = "root"//<-------------------------Sql Password
}
hibernate {
    cache.use_second_level_cache = true
    cache.use_query_cache = false
    cache.region.factory_class = 'net.sf.ehcache.hibernate.EhCacheRegionFactory'
}
// environment specific settings
environments {
    development {
        dataSource {
            dbCreate = " create-drop" // one of 'create', 'create-drop', 'update', 'validate', ''
            url = "jdbc:mysql://localhost/MysqlDemo"
       
// jdbc:mysql:<------------------------------jdbc mysql Driver
//Localhost<--------------------------------ServerRunning Under
//MysqlDemo<-----------------------------DataBaseSchema
}
    }
// for test and production is also same like devolopment
    test {
        dataSource {
            dbCreate = "update"
            url = "jdbc:mysql://localhost/ MysqlDemo "
        }
    }
    production {
        dataSource {
            dbCreate = "update"
            url = "jdbc:mysql://localhost/ MysqlDemo "
            pooled = true
            properties {
               maxActive = -1
               minEvictableIdleTimeMillis=1800000
               timeBetweenEvictionRunsMillis=1800000
               numTestsPerEvictionRun=3
               testOnBorrow=true
               testWhileIdle=true
               testOnReturn=true
               validationQuery="SELECT 1"
            }
        }
    }
}


Step2:Open following path and remove comment line like this

         C:/MysqlDemo/grails-app/conf/BuildConfig.groovy
        // runtime 'mysql:mysql-connector-java:5.1.20' //<----------------Remove Comment On Line 37
          
Then The code will be

grails.servlet.version = "2.5" // Change depending on target container compliance (2.5 or 3.0)
grails.project.class.dir = "target/classes"
grails.project.test.class.dir = "target/test-classes"
grails.project.test.reports.dir = "target/test-reports"
grails.project.target.level = 1.6
grails.project.source.level = 1.6
//grails.project.war.file = "target/${appName}-${appVersion}.war"

grails.project.dependency.resolution = {
    // inherit Grails' default dependencies
    inherits("global") {
        // specify dependency exclusions here; for example, uncomment this to disable ehcache:
        // excludes 'ehcache'
    }
    log "error" // log level of Ivy resolver, either 'error', 'warn', 'info', 'debug' or 'verbose'
    checksums true // Whether to verify checksums on resolve

    repositories {
        inherits true // Whether to inherit repository definitions from plugins

        grailsPlugins()
        grailsHome()
        grailsCentral()

        mavenLocal()
        mavenCentral()

        // uncomment these (or add new ones) to enable remote dependency resolution from public Maven repositories
        //mavenRepo "http://snapshots.repository.codehaus.org"
        //mavenRepo "http://repository.codehaus.org"
        //mavenRepo "http://download.java.net/maven/2/"
        //mavenRepo "http://repository.jboss.com/maven2/"
    }
    dependencies {
        // specify dependencies here under either 'build', 'compile', 'runtime', 'test' or 'provided' scopes eg.

        runtime 'mysql:mysql-connector-java:5.1.20'
    }

    plugins {
        runtime ":hibernate:$grailsVersion"
        runtime ":jquery:1.7.2"
        runtime ":resources:1.1.6"

        // Uncomment these (or add new ones) to enable additional resources capabilities
        //runtime ":zipped-resources:1.0"
        //runtime ":cached-resources:1.0"
        //runtime ":yui-minify-resources:0.1.4"

        build ":tomcat:$grailsVersion"

        runtime ":database-migration:1.1"

        compile ':cache:1.0.0'
    }
}


Step3:Open MysqlDataBase

                 mysql> Create  schema MysqlDemo
                           -> ;
                              Query OK, 1 row affected (0.00 sec)

                                mysql> use MysqlDemo;
                                Database changed
                                mysql> show tables;
                                Empty set (0.00 sec)

Step4:    grails run-app


Step5: enter the data like this


Step6: know in data base u can see output like this


Step7:Off the Server


Step8: in data base all tables are droped



Note to avoid this in DataSource.groovy
in devolopment Remove "create-drop" and rename as "Update"



3)How to get value from mysql table to our Grails Controlleri am doing modifications to above controller

Step1: go to following path and code like this


            C:/MysqlDemo/grails-app/controller/mysqlDemo/MysqlController.groovy
package mysqldemo
import groovy.sql.Sql
class MysqlController {
def scaffold=Mysql
def dataSource
def retrive={
def db = new Sql(dataSource)
def results12=db.rows("select DISTINCT  mysql.id,mysql.age,mysql.name,mysql.country from mysql ")
[results12:results12]
}}
           

Step2: create a view in folloing path and code like this

C:/MysqlDemo/grails-app/Views/mysql/retrive.gsp
<!DOCTYPE html>
<html>
                <head>
<meta name="layout" content="main">
</head>
<body>
<table>
                <g:each var="s" in="${results12}">
               
                                <tr>
                                                <td>
                <h1>    ${s.id}</h1>
</td><td>
                <h1>    ${s.name}</h1></td><td>
                <h1>    ${s.age}</h1></td><td>
                <h1>    ${s.country}</h1></td></tr>
                                                                                               
                </g:each>
</table>
</body>
</html>



Step:3 now run this application


grails run-app

 and enter the data in database data is stored like this in mysql






     Step4:If  u whant to retrive data from db then type like this in address bar

               http://localhost:8080/MysqlDemo/mysql/retrive
              from db it will retrieves data like this





 part5: How to build Relations model on mysql db




      
 

        



Sunday, 9 September 2012


HI THIS TOUTORIAL WILL HELP FULL FOR STARTUP IN GRAILS CREATED BY NAVEENRAJU
Parts




Part3:

1.creating a simple domain class which will perform(save,show,edit,delete) operations

  with scaffold in controller


Step1: grails create-app UsingScaffolding

 Step2:     cd  UsingScaffolding

Step3:grails  create-domain-class Demo1

Step4: open folloing path and type this code

         c:/ UsingScaffolding/grails-app/domain/usingScaffolding/Demo1.groovy

   package usingscaffolding
class Demo1 {
String   name
Integer  age
String   sex
String  country
}

Step5: go to cmd promt and create one controoler

           grails  create-controller Demo1

Step6: Open folloing path and type code like this

                     c:/ UsingScaffolding/grails-app/controllers/usingScaffolding/Demo1Controller.groovy
          package usingscaffolding
class Demo1Controller {
    def scaffold=Demo1
}

      step7:run this application

                grails run-app

     step8:open any Browser And type this url

 http://localhost:8080/UsingScaffolding


  step9: then click this link 

              usingscaffolding.Demo1Controller
               


step10: Then list page is opened  Afterwords click  NewDemo1 link

·                      

step11: fill the form and click create link



step12:After filling form then click  on create link show page will Open if u whant to edit click edit on link




step13:then edit  the page  after editing click update


            

step14:if u whant  to delete press on delete link




Note : From the above domain class will perform (save,edit,show,delete) operations
            because  in controller we mention  "def scaffold= domainclassName " hence in back ground
            it will create  5views (form.gsp,create.gsp,edit.gsp,list.gsp,show.gsp)  And
            it will create  in controller  7 actions (list,create,save,edit,show,update,delete)
            in part 6 we will see how we generate an aplication with all features with out scaffold


2)How to do Search After doing all operations  i am searching  with name

   in o/p i will reteive name and country with respect to searched name

Step1: i am doing modifications on above controller

step2:     c:/ UsingScaffolding/grails-app/controllers/usingScaffolding/Demo1Controller.groovy

              and recode like this
package usingscaffolding
class Demo1Controller {
def scaffold=Demo1
def search = {
if (request.method == 'POST')
{
def quary1= Demo1.findAllByNameLike('%' + params.name + '%')
[quary1:quary1]
}}}


step3: with respect to controller action search  create view (search.gsp) in folloing  path

            c:/ UsingScaffolding/grails-app/views/demo1/search.gsp
        code like this
    <html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8"/>
<meta name="layout" content="main" />
<title>Search for The Names</title>
</head>
<body>
<div class="body">
<h1>Search for for The Names</h1>
<g:if test="${flash.message}">
<div class="message">${flash.message}</div>
</g:if>
<g:form action="search" method="post" >
<div class="dialog">
<table>
<tr class='prop'>
<td valign='top' class='name'>
<label for='city'>Name:</label>
</td>
<td valign='top' class='value'>
<input type="text" maxlength='30' name='name'>
</input>
</td>
</tr>
</table>
</div>
<div class="buttons">
<input type="submit" value="Search"
class="formbutton">
</input>
</div>
</g:form>
<div class="dialog">
<table>
<tbody>
<g:each in="${quary1}">
<tr class="prop">
      <td valign="top" class="name">  Names</td>
       <td valign="top" class="value"> ${it.name} </td>
 </tr>
<tr class="prop">
      <td valign="top" class="name"> Country</td>
       <td valign="top" class="value"> ${it.country} </td>
 </tr>
</g:each>
</tbody>
</table>                             
</div>
</div>
</body>
</html>

Note : <meta name="layout" content="main" />
            it will give grails Header  and u can use those classes

step4: go to command prompt and run the server

          grails run-app

   http://localhost:8080/UsingScaffolding/

step6:Enter the form up to 5 fields

      

step7:After entering fields in addressbar  type this url afterwords type name and seach


Step9:then  final output will be like this


            


 

  3) from above examle validations are there how to remove validations in DomainClass











step1:i am doing modifications on above domain class---->class  Demo1

step2: open folloing path 

        c:/ UsingScaffolding/grails-app/domain/usingScaffolding/Demo1.groovy
        re code like this
package usingscaffolding

class Demo1 {
String   name
Integer  age
String   sex
String  country
String  address
static constraints = {
age(nullable:true,blank:true)//in this nullabule,blank is acepted
sex(nullable:true,blank:true)//in this nullabule,blank is acepted
name(nullable:false,blank:false)//in this nullabule,blank is not acepted
country(nullable:false,blank:false)//in this nullabule,blank is not acepted
address(nullable:true,blank:true,size:3..500)/*in this nullabule,blank is acepted
                                               and textbox size will be 3to500*/
 }
}

step3: then the output will be like this









4.How To Pick Random list from above list it generated

step1: know i am doing modifications  on  Controller

step2:Open Folloing link

          c:/ UsingScaffolding/grails-app/controllers/usingScaffolding/Demo1Controller.groovy
  re code like this
 package usingscaffolding

class Demo1Controller {

    def scaffold=Demo1





def search = {
if (request.method == 'POST')
{
def quary1= Demo1.findAllByNameLike('%' + params.name + '%')
[quary1:quary1]
//render  model:[ raceList:Demo1.findAllByNameLike('%' + params.name + '%') ]
}
}

def random = {
def list = Demo1.list()
def raja
if (list.size() > 0) {
def randomPic = new Random().nextInt(list.size())
raja = list[randomPic]
} else {
 raja = new Demo1(name: "Raja",
age: "23",sex:"male",country:"India",address:"Hyderabad")
}
[ raja : raja]
}
}
         

step3:  with respect to controller action search  create view (search.gsp) in folloing  path

            c:/ UsingScaffolding/grails-app/views/demo1/random.gsp
     code like this
<html>
<head>
<title>Random</title>

</head>
<body>
<g:each in="${raja}">
<div id="raja">
<a>${it.name}</a>
<b>${it.country}</b>
<c>${it.age}</c>
<d>${it.sex}</d>
<e>${it.address}</e>
</div>
</g:each>
</body>
</html>

step4:run the application

           grails run-app
browse to above link

step5: Fill the form up to 5 fields


step6:type folloing url in address bar and refersh it for 10 times then it will pick random list details 






5)before  filling the form i am placing 1 field by using Bottstrap

Step1:from the above randompick example starting list is empty

         after filling the form only we can do random operation
        with out filling form  i am adding 1 row in list by this example after that u can fill list as usal
       but first row i am adding

step2: open folloing link  and create NaveenBootStarp.groovy

           c:/ UsingScaffolding/grails-app/conf/ NaveenBootStarp.groovy
           code like this in NaveenBootStrap.groovy
package usingscaffolding
class NaveenBootStrap {
def init = { servletContext ->
// We can Create some Test Data Here that are inserted in list
new Demo1(name: "Raja",age: "23",sex:"male",country:"India",address:"Hyderabad").save()

}
def destroy = {
}
}

step3:after that run this application

               grails run-app

step4:click on usingscaffolding.Demo1Controller

hence with out  filling form we can insert data to list by crating  ur ownBootStrap
in conf  folder