Groovy is a scripting language and not a music genre. But yes, this is one framework that is as easy
working with as listening to your favorite music! The reason being that it uses the
'coding by convention' method. Such a technique implies that names of some of
the files, artifacts, etc are self explanatory so they are not included in the
configuration files; the framework finds out by itself what is to be used where.
And the best part is that the business logic is auto-generated. Let's look at this framework and how
to build applications with it.
What is Grails?
Grails is a framework built on lines of the Rails framework. Rails is a Model-View-Controller based framework for Web
applications using technology like AJAX for viewing and a complete request-response
model for the controller. If you have used Rails, you would find Grails very easy to
use. But in case it is Java that has been your only means of creating software,
you won't find this one any tougher to get started with, as it is already based on Open Source
technologies like Spring and Hibernate. Grails also provides integration with technologies it is built upon, so your
Spring application doesn't need to be ripped apart for 'Grailing' it.
|
Grails is loaded with automated tasks for almost anything, from creating domain classes,
to OR (Object Relational) mapping, or creating domains, most of the time you would be running Ant commands from
command line to get the work done.
Groovy for Grails
Being a scripting language based on Java, it makes a lot of difference to Grails.
Groovy compiles to byte codes and it makes no difference to the Java platform if
the byte codes were generated from code written in Java or Groovy. The other advantages include ease of use in the context
that you don't necessarily need to wrap up every thing in a class while you're using
Groovy. In fact if you look at the documentation, a 'Hello World!' example would
simply contain the statement 'println(Hello World !)'without having to declare a class
and method for the same. Thus it does almost anything that Java does for a Web
application but it has lesser rules.
The Grails' Create-app command creates a detailed directory structure with almost all configuration files and artifacts auto-generated |
A Groovy application
You can find install instructions on the framework's website mentioned above. So
we'll get down to action straight away.To create an application you need to run the task
grails create-app
The command prompts for application name (PCQG Demo in our case).
This creates an elaborate directory structure as well as
configuration files and all other artifacts commonly used in a Web application.
With the skeletal structure ready we'll add some life to it by building a
simple application.
Our application simply displays products, customers and orders
from a database, of course there is a lot more that you can add to this
application, but for the sake of simplicity, we'll stick to this one. The
database we're using is created on MySQL and is named 'test'. It has three
tables, customer, product, and order_data. First create classes for each of the
database entities. This is done using the following command from the root
directory of your product.
grails create-domain-class
The command prompts for class name and generates a
class under the
test suite under the
created three classes viz.Customer,Product, and Order.The classes created will
initially have only two attributes viz.'id'and 'version'.The classes can
then be edited as follows:
class Customer{
Long id
Long version
Integer customerid
String name = '
def relatesToMany = < products :
Product, orders : Order >
Set orders = new HashSet()
Set products = new HashSet()
String toString() {
"${this.class.name} : $id" }
boolean equals(other) {
if(other?.is(this))return true
if(!(other instanceof Customer)) return
false
if(!id || !other?.id || id!=other?.id)
return false
return true
}
}
For the name attribute we are providing a default value 'customer'
in case the field is left blank. The notation
purpose. The statement 'def relatesToMany' provides the mapping for the
relationship between customer and order, products table which is one to many.
Similarly, you can edit the class Product which has the attributes: productid
(integer), code, name (both strings) and unitprice (double). The order class we
created will map to a table called order_data in our database. To configure this
mapping, all you have to do is use the 'withTable' keyword as follows:
class Order{
...
static withTable =
"order_data"
Integer orderid
Integer customerid
Date orderdate
Integer quantity
def belongsTo = Customer
...
}
Once we are through with our classes we will configure our application to use
the MySQL database.Groovy defines three modes for Data Sources in three
different files under the
In the Order List page from the PCQGDemo application, the page navigation is configured with links for common tasks like order list and new order |
These are: Development mode defined in file DevelopmentData
Source.groovy,Productionmode defined in ProductionDataSource.groovy, and
Test mode defined in TestDataSource. groovy. For our application we will take
the Development data source and configure it for MySQL as follows:
class DevelopmentDataSource {
boolean pooling = true
def logSql = true
String dbCreate = "create-drop"
String url =
"jdbc:mysql://localhost/grailsDB"
String driverClassName =
"org.gjt.mm.mysql.Driver"
String username = "username"
String password = "password"
}
You need to download the latest stable version of MySQL Connector for Java
and copy the JAR file into the
and data sources defined, we will now look into defining controllers for each of
the domain classes. This is where we were impressed the most with this
framework, and this is how you create controller.
grails generate-all
The only input you give here is the class for which you want to generate
controllers, so run this three times and provide names of all classes you have
created. The following code is a bit long, taken straight from the application
we created, and it is auto-generated, so practically you don't scribble a
single word of code for the controllers.
class CustomerController {
def index = {
redirect(action:list,params:params) }
def allowedMethods =
save:'POST',
update:'POST'>
def list = {
if(!params.max)params.max = 10
< customerList: Customer.list(
params ) >
}
def show = {
< customer : Customer.get(
params.id ) >
}
def delete = {
def customer = Customer.get(
params.id )
if(customer) {
customer.delete()
flash.message = "Customer
${params.id} deleted."
redirect(action:list)
}
else {
flash.message = "Customer not
found with id ${params.id}"
redirect(action:list)
}
}
def edit = {
def customer = Customer.get(
params.id )
if(!customer) {
flash.message = "Customer
not found with id ${params.id}"
redirect(action:list)
}
else {
return < customer : customer >
}
}
def update = {
def customer = Customer.get(
params.id )
if(customer) {
customer.properties = params
if(customer.save()) {
redirect(action:show,id:customer.
id)
}
else {
render(view:'edit',model:
customer>)
}
}
else {
flash.message = "Customer not
found with id ${params.id}"
redirect(action:edit,id:params.id)
}
}
def create = {
def customer = new Customer()
customer.properties = params
return <'customer':customer>
}
def save = {
def customer = new Customer()
customer.properties = params
if(customer.save()) {
redirect(action:show,id:customer.
id)
}
else {
render(view:'create',model:
customer>)
}
}
}
Now if you look at the code, you'll realize that it contains all the
business logic. That's the real advantage over here.
After you're through with domain classes; almost everything is
auto-generated. To run the application, we again have three modes, the
production (default) mode, the development mode, and the test mode.The commands
to be issued in each case respectively are:
grails run-app //default mode
grails dev run-app // development mode
grails test run-app // test mode
So all you need to do is issue the command for development mode and you will
find your application up and running when you enter the following
address in the browser: http://localhost:8080/PCQGDemo
Conclusion
A one-stop solution for quickly building enterprise scale applications, in
fact their home page lists quite a few impressive projects using the framework.
If you still want more (for a reason you will have to figure out!) the framework
is easily integrable even with AJAX.