SlideShare a Scribd company logo
Building Grails Applications
                       with PostgreSQL
                            Brent Baxter and Ken Rimple
                          PostgreSQL East - March 25, 2010




Tuesday, March 30, 2010
About Brent and Ken
             • Brent Baxter: bbaxter@chariotsolutions.com
                   ‣ Consultant and Applications Architect
                   ‣ Grails, Java, and Spring developer
             • Ken Rimple: krimple@chariotsolutions.com
                   ‣ Head of Education Services
                   ‣ Host, Chariot TechCast:
                          http://techcast.chariotsolutions.com
                                   PostgreSQL East - March 25, 2010


Tuesday, March 30, 2010
About Chariot Solutions

             • Java and Open Source solutions provider
             • Chariot Solutions Education Services
                   ‣ Groovy and Grails training and mentoring
             • Chariot Solutions Consulting
                   ‣ Development and consulting services
             • http://www.chariotsolutions.com
                                 PostgreSQL East - March 25, 2010


Tuesday, March 30, 2010
Goals


             • Provide a basic overview of the Grails
                     framework - with a dash of Groovy
             • Review some of the features of Grails Object
                     Relational Modeling (GORM)
             • Demonstrate Grails with PostgreSQL

                                   PostgreSQL East - March 25, 2010


Tuesday, March 30, 2010
Introduction to Groovy



                                 PostgreSQL East - March 25, 2010


Tuesday, March 30, 2010
Groovy

             • A dynamic language built for the Java Virtual
                     Machine
                   ‣ Compiles to native ByteCode
                   ‣ Can inherit Groovy classes from Java classes
                     (and vice versa)
                   ‣ Native access to any Java library


                                  PostgreSQL East - March 25, 2010


Tuesday, March 30, 2010
Benefits of Groovy

             • Adds "Convention over Configuration"
                   ‣ Groovy beans are VERY simple
                   ‣ Assumes methods are public, member
                     variables are private
                   ‣ Constructors not required
                   ‣ Easy collections – Use the [ ] syntax for lists
                     and maps

                                   PostgreSQL East - March 25, 2010


Tuesday, March 30, 2010
A Sampling of Groovy APIs
             •      xml – Powerful XML                      •    builders – a set of
                    Parsing, Creation                            repetitive building tasks can
                                                                 be automated using various
             •      gsql – Simplified JDBC API                    Groovy Builders

             •      Groovy Testing– simple                  •    Swing – the Groovy
                    testing API, mocking with                    SwingBuilder makes UI
                    closures, etc...                             easy. Also Griffon is a
                                                                 Groovy-based MVC
             •      Collections – lists, maps                    framework for Swing (like
                                                                 Grails for Web)
                    and ranges




                                         PostgreSQL East - March 25, 2010


Tuesday, March 30, 2010
Java Person Class
                          public class Person {
                            private String firstName;
                            private String lastName;
                            private Date birthDate;

                              public Person(String firstName,
                                    String lastName, Date birthDate) {
                                  ...
                              }

                              public void setFirstName() { ... }
                              public String getFirstName() { ... }

                              // etc...
                          }


                                          PostgreSQL East - March 25, 2010


Tuesday, March 30, 2010
Groovy Person Class


                          class Person {
                            String lastName
                            String firstName
                            Date birthDate
                          }




                               PostgreSQL East - March 25, 2010


Tuesday, March 30, 2010
Constructors and Lists

       // Groovy provides constructors for free
       def bob = new Person(firstName:'Bob', lastName:'Smith')
       def sue = new Person(firstName:'Sue', lastName:'Jones',
                      birthDate:new Date('8/12/1974'))




       // ArrayLists are simple
       def persons = [ new Person(firstName:‘Bob’),
                                 new Person(firstName:‘Sue’)]

       persons += new Person(firstName:‘John’)



                              PostgreSQL East - March 25, 2010


Tuesday, March 30, 2010
Groovy SQL Support


                  // Using JDBC

                  def sql = Sql.newInstance(url, usr, pwd, driver)
                  sql.execute(“insert into table values ($foo, $bar)”)
                  sql.execute(“insert into table values (?,?)”, [a,b])
                  sql.eachRow(“select * from USER”) {println it.name}
                  def list = sql.rows(“select * from USER”)




                                    PostgreSQL East - March 25, 2010


Tuesday, March 30, 2010
Introduction to Grails



                                PostgreSQL East - March 25, 2010


Tuesday, March 30, 2010
Grails Framework

             • A web application framework
                   ‣ Three-tiered Model View Controller (MVC)
             • Convention based
                   ‣ Sensible default configuration or use any of a
                     number of simple DSLs
             • Extendable with a rich set of plug-ins
                                  PostgreSQL East - March 25, 2010


Tuesday, March 30, 2010
Grails Is Groovy

             • Leverages the Groovy programing language
                   ‣ Groovy Services and Beans
             • Configuration DSLs
                   ‣ Logging, data source configuration,
                     dependency resolution, ...
             • Web tier Groovy Server Pages (GSP)
                                  PostgreSQL East - March 25, 2010


Tuesday, March 30, 2010
Grails Is Java

             • Framework backed by best of breed industry
                     standards
                   ‣ Spring, Hibernate, SiteMesh, Web Flow, etc.
             • Leverage any Java library, access from Groovy or
                     Java classes
             • Can be deployed as a Java web application
                     (WAR) to any Servlet container

                                    PostgreSQL East - March 25, 2010


Tuesday, March 30, 2010
Grails Technology Stack

                                      Grails

                                                        Standard
               SiteMesh Spring Hibernate                            Groovy
                                                        Libraries

                                    Java API

                            Java Platform (JVM)


                              PostgreSQL East - March 25, 2010


Tuesday, March 30, 2010
Key Grails Components

             • Domain Class - A class representing an object in
                     your domain (database table)
             • Controller - A class that operates on URLs
                     submitted to the web site
             • View - A Groovy Server Page (GSP) designed to
                     render the content based on a specific request


                                   PostgreSQL East - March 25, 2010


Tuesday, March 30, 2010
Domain Driven Design with Grails
             • Focus on the complexities of the domain first
             • Create domain objects and their relationships
                     first
             • Dynamically 'scaffold' controllers and views for
                     each domain class, validate domain objects and
                     relationships
             • When ready, finish by generating or coding all
                     views, controllers, and tests

                                     PostgreSQL East - March 25, 2010


Tuesday, March 30, 2010
Grails Scaffolding
             • Dynamically generated views based on default
                     templates
             • No need to define a page before completing the
                     data model

                 // Domain                         // Dynamic Scaffold Controller
                 class Person {                    class PersonController {
                   String firstName                   def scaffold = true
                   String lastName                 }
                   Date birthDate
                 }



                                      PostgreSQL East - March 25, 2010


Tuesday, March 30, 2010
More than a web framework...
             • Eases development of every tier
                   ‣ Integrated Groovy build system
                   ‣ Integrated Groovy unit and integration test
                     mechanism
                   ‣ Simple ORM based on Hibernate
                   ‣ Extensible plug-in system built on Spring
                   ‣ Also simplifies Web MVC

                                  PostgreSQL East - March 25, 2010


Tuesday, March 30, 2010
Grails Object Relational
                            Mapping (GORM)



                                 PostgreSQL East - March 25, 2010


Tuesday, March 30, 2010
GORM
             • Grails Object Relational Mapping API
                   ‣ Uses domain classes written in Groovy
                   ‣ Injects methods into domain classes for load,
                     save, update, and query data
                   ‣ Backed by Hibernate and Spring
                   ‣ Write Hibernate objects without all of the
                     messy XML!

                                  PostgreSQL East - March 25, 2010


Tuesday, March 30, 2010
GORM Benefits

             • Write your domain classes as POGOs
             • Define validation via constraints
             • Define relationships via simple belongsTo,
                     hasMany mappings
             • Easy to test framework, can use grails console
                     or grails shell, even integration tests
             • Finders make it easy to locate data
                                     PostgreSQL East - March 25, 2010


Tuesday, March 30, 2010
Grails Domain Classes

             • Created with create-domain-class
             • Simple Groovy Beans
                   ‣ Each member variable represents a column in
                     a table
                   ‣ Implied version, primary key fields
                   ‣ Can define relationships with other domains,
                     validation constraints

                                  PostgreSQL East - March 25, 2010


Tuesday, March 30, 2010
Connecting to PostgreSQL

             • Grails defines database connections for various
                     environments (Development, Test, Production)
             • Steps to configure your database
                   ‣ Install your database driver
                   ‣ Modify grails-app/config/DataSource.groovy
                   ‣ Boot grails with grails run-app


                                   PostgreSQL East - March 25, 2010


Tuesday, March 30, 2010
Defining Constraints
                                      class Customer {
                •     Checked
                      automatically        static constraints = {
                      when saved             firstName(maxLength: 15, blank: false)
                                             lastName(maxLength: 20, blank: false)
                      or when                registrationDate(nullable: false)
                      validate() is          preferredCustomer(default: true)
                      called                 awardsBalance(range: 0.0..5000.0)
                                           }
                                           String firstName
                •     Tip: scaffold        String lastName
                      configuration         Date registrationDate
                                           Boolean preferredCustomer
                      follows              BigDecimal awardsBalance
                      constraint      }
                      order for
                      field order


                                          PostgreSQL East - March 25, 2010


Tuesday, March 30, 2010
Entity Relationships

             • Grails supports all Hibernate relation mappings
                   ‣ One to One
                   ‣ One to Many
                   ‣ Many to Many
                   ‣ Parent/Child (Inheritence)


                                  PostgreSQL East - March 25, 2010


Tuesday, March 30, 2010
One to many relationship
        • Customer 'owns' accounts (cascade deletes, updates, saves)
          class Customer {
                                                            class Account {
                 String firstName
                                                                static belongsTo =
                 String lastName
                                                                       [customer:Customer]
                 ...
                                                                   String accountNumber
               static hasMany = [accounts:Account]
                                                            }
          }


              // arbitrary but working example... flush for testing only...
              def customer = new Customer(firstName: "Dude", lastName: "WheresMyCar")
              def account = new Account(accountNumber:"1234", customer:customer)
              customer.accounts = [account]
              def result = customer.save(flush:true)

              def account2 = Account.findById(account.id)
              println account2.customer

              def customer2 = Customer.findById(customer.id)
              println customer2.accounts

                                          PostgreSQL East - March 25, 2010


Tuesday, March 30, 2010
Physical DB Settings - mapping
             • Changing the table, versioning on/off, column
                     mappings, indexing, multi-column-index, etc...
       class Person {
       String firstName
       String address
          static mapping = {
             table 'people'
             version false
             id column:'person_id'
             firstName column:'First_Name', index:'Name_Idx'
             address column:'Address', index:'Name_Idx, Address_Index'
          }
       }



                                    PostgreSQL East - March 25, 2010


Tuesday, March 30, 2010
Stored Procedures

             • Several approaches
                   ‣ Spring's JdbcTemplate
                   ‣ Spring's StoredProcedure class
                   ‣ Spring's SqlFunction
                   ‣ Groovy SQL
             • Demonstration
                                  PostgreSQL East - March 25, 2010


Tuesday, March 30, 2010
Where to find the code


             • Hit our GitHub repository (you can just ask to
                     download the files)
             • GitHub repo for our samples
                   ‣ github.com/krimple/Grails-Demos-
                     PostgreSQL-East-2010.git



                                   PostgreSQL East - March 25, 2010


Tuesday, March 30, 2010
Groovy and Grails Resources

             • Grails Web Site
                   ‣ http://www.grails.org
             • Grails User Email List
                   ‣ http://n4.nabble.com/Grails-f1312388.html
             • Groovy Web Site
                   ‣ http://groovy.codehaus.org/

                                  PostgreSQL East - March 25, 2010


Tuesday, March 30, 2010
Free InfoQ E-Book

             •      Getting Started with Grails,
                    Second Edition

                   ‣ Scott Davis

                   ‣ Jason Rudolph

             •      http://www.infoq.com/
                    minibooks/grails-getting-
                    started


                                        PostgreSQL East - March 25, 2010


Tuesday, March 30, 2010
Regional User Groups

             • Philadelphia Groovy and Grails User Group
                   ‣ http://phillygroovy.org
                   ‣ Meet-up April 8 as part of Philly ETE
             • Philadelphia Spring User Group
                   ‣ http://phillyspring.ning.com/


                                   PostgreSQL East - March 25, 2010


Tuesday, March 30, 2010
Thank you!

                          Questions ... ?


                             PostgreSQL East - March 25, 2010


Tuesday, March 30, 2010

More Related Content

What's hot (20)

Introduction à spring boot
Introduction à spring bootIntroduction à spring boot
Introduction à spring boot
Antoine Rey
 
Json Web Token - JWT
Json Web Token - JWTJson Web Token - JWT
Json Web Token - JWT
Prashant Walke
 
Spring Boot
Spring BootSpring Boot
Spring Boot
HongSeong Jeon
 
Modern Java web applications with Spring Boot and Thymeleaf
Modern Java web applications with Spring Boot and ThymeleafModern Java web applications with Spring Boot and Thymeleaf
Modern Java web applications with Spring Boot and Thymeleaf
LAY Leangsros
 
Java 9 New Features
Java 9 New FeaturesJava 9 New Features
Java 9 New Features
Ali BAKAN
 
Spring Data JPA from 0-100 in 60 minutes
Spring Data JPA from 0-100 in 60 minutesSpring Data JPA from 0-100 in 60 minutes
Spring Data JPA from 0-100 in 60 minutes
VMware Tanzu
 
Meta Programming in Groovy
Meta Programming in GroovyMeta Programming in Groovy
Meta Programming in Groovy
NexThoughts Technologies
 
카카오 광고 플랫폼 MSA 적용 사례 및 API Gateway와 인증 구현에 대한 소개
카카오 광고 플랫폼 MSA 적용 사례 및 API Gateway와 인증 구현에 대한 소개카카오 광고 플랫폼 MSA 적용 사례 및 API Gateway와 인증 구현에 대한 소개
카카오 광고 플랫폼 MSA 적용 사례 및 API Gateway와 인증 구현에 대한 소개
if kakao
 
AEM hacker - approaching Adobe Experience Manager webapps in bug bounty programs
AEM hacker - approaching Adobe Experience Manager webapps in bug bounty programsAEM hacker - approaching Adobe Experience Manager webapps in bug bounty programs
AEM hacker - approaching Adobe Experience Manager webapps in bug bounty programs
Mikhail Egorov
 
spring-api-rest.pdf
spring-api-rest.pdfspring-api-rest.pdf
spring-api-rest.pdf
Jaouad Assabbour
 
Testing with Spring, AOT, GraalVM, and JUnit 5 - Spring I/O 2023
Testing with Spring, AOT, GraalVM, and JUnit 5 - Spring I/O 2023Testing with Spring, AOT, GraalVM, and JUnit 5 - Spring I/O 2023
Testing with Spring, AOT, GraalVM, and JUnit 5 - Spring I/O 2023
Sam Brannen
 
cours java complet-2.pdf
cours java complet-2.pdfcours java complet-2.pdf
cours java complet-2.pdf
Jaouad Assabbour
 
이벤트 기반 분산 시스템을 향한 여정
이벤트 기반 분산 시스템을 향한 여정이벤트 기반 분산 시스템을 향한 여정
이벤트 기반 분산 시스템을 향한 여정
Arawn Park
 
Introduction à React JS
Introduction à React JSIntroduction à React JS
Introduction à React JS
Abdoulaye Dieng
 
JVM++: The Graal VM
JVM++: The Graal VMJVM++: The Graal VM
JVM++: The Graal VM
Martin Toshev
 
[오픈소스컨설팅]Scouter 설치 및 사용가이드(JBoss)
[오픈소스컨설팅]Scouter 설치 및 사용가이드(JBoss)[오픈소스컨설팅]Scouter 설치 및 사용가이드(JBoss)
[오픈소스컨설팅]Scouter 설치 및 사용가이드(JBoss)
Ji-Woong Choi
 
Networking in Java with NIO and Netty
Networking in Java with NIO and NettyNetworking in Java with NIO and Netty
Networking in Java with NIO and Netty
Constantine Slisenka
 
Lambda Expressions in Java
Lambda Expressions in JavaLambda Expressions in Java
Lambda Expressions in Java
Erhan Bagdemir
 
Laravel introduction
Laravel introductionLaravel introduction
Laravel introduction
Simon Funk
 
OLTP+OLAP=HTAP
 OLTP+OLAP=HTAP OLTP+OLAP=HTAP
OLTP+OLAP=HTAP
EDB
 
Introduction à spring boot
Introduction à spring bootIntroduction à spring boot
Introduction à spring boot
Antoine Rey
 
Modern Java web applications with Spring Boot and Thymeleaf
Modern Java web applications with Spring Boot and ThymeleafModern Java web applications with Spring Boot and Thymeleaf
Modern Java web applications with Spring Boot and Thymeleaf
LAY Leangsros
 
Java 9 New Features
Java 9 New FeaturesJava 9 New Features
Java 9 New Features
Ali BAKAN
 
Spring Data JPA from 0-100 in 60 minutes
Spring Data JPA from 0-100 in 60 minutesSpring Data JPA from 0-100 in 60 minutes
Spring Data JPA from 0-100 in 60 minutes
VMware Tanzu
 
카카오 광고 플랫폼 MSA 적용 사례 및 API Gateway와 인증 구현에 대한 소개
카카오 광고 플랫폼 MSA 적용 사례 및 API Gateway와 인증 구현에 대한 소개카카오 광고 플랫폼 MSA 적용 사례 및 API Gateway와 인증 구현에 대한 소개
카카오 광고 플랫폼 MSA 적용 사례 및 API Gateway와 인증 구현에 대한 소개
if kakao
 
AEM hacker - approaching Adobe Experience Manager webapps in bug bounty programs
AEM hacker - approaching Adobe Experience Manager webapps in bug bounty programsAEM hacker - approaching Adobe Experience Manager webapps in bug bounty programs
AEM hacker - approaching Adobe Experience Manager webapps in bug bounty programs
Mikhail Egorov
 
Testing with Spring, AOT, GraalVM, and JUnit 5 - Spring I/O 2023
Testing with Spring, AOT, GraalVM, and JUnit 5 - Spring I/O 2023Testing with Spring, AOT, GraalVM, and JUnit 5 - Spring I/O 2023
Testing with Spring, AOT, GraalVM, and JUnit 5 - Spring I/O 2023
Sam Brannen
 
이벤트 기반 분산 시스템을 향한 여정
이벤트 기반 분산 시스템을 향한 여정이벤트 기반 분산 시스템을 향한 여정
이벤트 기반 분산 시스템을 향한 여정
Arawn Park
 
Introduction à React JS
Introduction à React JSIntroduction à React JS
Introduction à React JS
Abdoulaye Dieng
 
[오픈소스컨설팅]Scouter 설치 및 사용가이드(JBoss)
[오픈소스컨설팅]Scouter 설치 및 사용가이드(JBoss)[오픈소스컨설팅]Scouter 설치 및 사용가이드(JBoss)
[오픈소스컨설팅]Scouter 설치 및 사용가이드(JBoss)
Ji-Woong Choi
 
Networking in Java with NIO and Netty
Networking in Java with NIO and NettyNetworking in Java with NIO and Netty
Networking in Java with NIO and Netty
Constantine Slisenka
 
Lambda Expressions in Java
Lambda Expressions in JavaLambda Expressions in Java
Lambda Expressions in Java
Erhan Bagdemir
 
Laravel introduction
Laravel introductionLaravel introduction
Laravel introduction
Simon Funk
 
OLTP+OLAP=HTAP
 OLTP+OLAP=HTAP OLTP+OLAP=HTAP
OLTP+OLAP=HTAP
EDB
 

Similar to Building Grails applications with PostgreSQL (20)

Groovy and Grails talk
Groovy and Grails talkGroovy and Grails talk
Groovy and Grails talk
desistartups
 
Groovy and Grails intro
Groovy and Grails introGroovy and Grails intro
Groovy and Grails intro
Miguel Pastor
 
Whats New In Groovy 1.6?
Whats New In Groovy 1.6?Whats New In Groovy 1.6?
Whats New In Groovy 1.6?
Guillaume Laforge
 
Grails Integration Strategies
Grails Integration StrategiesGrails Integration Strategies
Grails Integration Strategies
daveklein
 
Groovy Tutorial
Groovy TutorialGroovy Tutorial
Groovy Tutorial
Paul King
 
Groovy And Grails Introduction
Groovy And Grails IntroductionGroovy And Grails Introduction
Groovy And Grails Introduction
Eric Weimer
 
Grails 101
Grails 101Grails 101
Grails 101
David Jacobs
 
Gg Code Mash2009 20090106
Gg Code Mash2009 20090106Gg Code Mash2009 20090106
Gg Code Mash2009 20090106
Jim Shingler
 
In pursuit of expressivity: Groovy and Scala compared
In pursuit of expressivity: Groovy and Scala comparedIn pursuit of expressivity: Groovy and Scala compared
In pursuit of expressivity: Groovy and Scala compared
Chris Richardson
 
Java Edge.2009.Grails.Web.Dev.Made.Easy
Java Edge.2009.Grails.Web.Dev.Made.EasyJava Edge.2009.Grails.Web.Dev.Made.Easy
Java Edge.2009.Grails.Web.Dev.Made.Easy
roialdaag
 
A Tour Through the Groovy Ecosystem
A Tour Through the Groovy EcosystemA Tour Through the Groovy Ecosystem
A Tour Through the Groovy Ecosystem
Leonard Axelsson
 
Groovygrailsnetbeans 12517452668498-phpapp03
Groovygrailsnetbeans 12517452668498-phpapp03Groovygrailsnetbeans 12517452668498-phpapp03
Groovygrailsnetbeans 12517452668498-phpapp03
Kevin Juma
 
Overview of Grails Object Relational Mapping (GORM)
Overview of Grails Object Relational Mapping (GORM)Overview of Grails Object Relational Mapping (GORM)
Overview of Grails Object Relational Mapping (GORM)
Chris Richardson
 
Oscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast LaneOscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast Lane
Andres Almiray
 
OpenLogic
OpenLogicOpenLogic
OpenLogic
webuploader
 
Introduction to Grails 2013
Introduction to Grails 2013Introduction to Grails 2013
Introduction to Grails 2013
Gavin Hogan
 
groovy and concurrency
groovy and concurrencygroovy and concurrency
groovy and concurrency
Paul King
 
Polyglot Grails
Polyglot GrailsPolyglot Grails
Polyglot Grails
Marcin Gryszko
 
Groovy 1 7 Update, past, present, future - S2G Forum 2010
Groovy 1 7 Update, past, present, future - S2G Forum 2010Groovy 1 7 Update, past, present, future - S2G Forum 2010
Groovy 1 7 Update, past, present, future - S2G Forum 2010
Guillaume Laforge
 
Paulking groovy
Paulking groovyPaulking groovy
Paulking groovy
d0nn9n
 
Groovy and Grails talk
Groovy and Grails talkGroovy and Grails talk
Groovy and Grails talk
desistartups
 
Groovy and Grails intro
Groovy and Grails introGroovy and Grails intro
Groovy and Grails intro
Miguel Pastor
 
Grails Integration Strategies
Grails Integration StrategiesGrails Integration Strategies
Grails Integration Strategies
daveklein
 
Groovy Tutorial
Groovy TutorialGroovy Tutorial
Groovy Tutorial
Paul King
 
Groovy And Grails Introduction
Groovy And Grails IntroductionGroovy And Grails Introduction
Groovy And Grails Introduction
Eric Weimer
 
Gg Code Mash2009 20090106
Gg Code Mash2009 20090106Gg Code Mash2009 20090106
Gg Code Mash2009 20090106
Jim Shingler
 
In pursuit of expressivity: Groovy and Scala compared
In pursuit of expressivity: Groovy and Scala comparedIn pursuit of expressivity: Groovy and Scala compared
In pursuit of expressivity: Groovy and Scala compared
Chris Richardson
 
Java Edge.2009.Grails.Web.Dev.Made.Easy
Java Edge.2009.Grails.Web.Dev.Made.EasyJava Edge.2009.Grails.Web.Dev.Made.Easy
Java Edge.2009.Grails.Web.Dev.Made.Easy
roialdaag
 
A Tour Through the Groovy Ecosystem
A Tour Through the Groovy EcosystemA Tour Through the Groovy Ecosystem
A Tour Through the Groovy Ecosystem
Leonard Axelsson
 
Groovygrailsnetbeans 12517452668498-phpapp03
Groovygrailsnetbeans 12517452668498-phpapp03Groovygrailsnetbeans 12517452668498-phpapp03
Groovygrailsnetbeans 12517452668498-phpapp03
Kevin Juma
 
Overview of Grails Object Relational Mapping (GORM)
Overview of Grails Object Relational Mapping (GORM)Overview of Grails Object Relational Mapping (GORM)
Overview of Grails Object Relational Mapping (GORM)
Chris Richardson
 
Oscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast LaneOscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast Lane
Andres Almiray
 
Introduction to Grails 2013
Introduction to Grails 2013Introduction to Grails 2013
Introduction to Grails 2013
Gavin Hogan
 
groovy and concurrency
groovy and concurrencygroovy and concurrency
groovy and concurrency
Paul King
 
Groovy 1 7 Update, past, present, future - S2G Forum 2010
Groovy 1 7 Update, past, present, future - S2G Forum 2010Groovy 1 7 Update, past, present, future - S2G Forum 2010
Groovy 1 7 Update, past, present, future - S2G Forum 2010
Guillaume Laforge
 
Paulking groovy
Paulking groovyPaulking groovy
Paulking groovy
d0nn9n
 
Ad

More from Command Prompt., Inc (20)

Howdah - An Application using Pylons, PostgreSQL, Simpycity and Exceptable
Howdah - An Application using Pylons, PostgreSQL, Simpycity and ExceptableHowdah - An Application using Pylons, PostgreSQL, Simpycity and Exceptable
Howdah - An Application using Pylons, PostgreSQL, Simpycity and Exceptable
Command Prompt., Inc
 
Backup and-recovery2
Backup and-recovery2Backup and-recovery2
Backup and-recovery2
Command Prompt., Inc
 
Mastering PostgreSQL Administration
Mastering PostgreSQL AdministrationMastering PostgreSQL Administration
Mastering PostgreSQL Administration
Command Prompt., Inc
 
Temporal Data
Temporal DataTemporal Data
Temporal Data
Command Prompt., Inc
 
Replication using PostgreSQL Replicator
Replication using PostgreSQL ReplicatorReplication using PostgreSQL Replicator
Replication using PostgreSQL Replicator
Command Prompt., Inc
 
Go replicator
Go replicatorGo replicator
Go replicator
Command Prompt., Inc
 
Pg migrator
Pg migratorPg migrator
Pg migrator
Command Prompt., Inc
 
Python utilities for data presentation
Python utilities for data presentationPython utilities for data presentation
Python utilities for data presentation
Command Prompt., Inc
 
PostgreSQL, Extensible to the Nth Degree: Functions, Languages, Types, Rules,...
PostgreSQL, Extensible to the Nth Degree: Functions, Languages, Types, Rules,...PostgreSQL, Extensible to the Nth Degree: Functions, Languages, Types, Rules,...
PostgreSQL, Extensible to the Nth Degree: Functions, Languages, Types, Rules,...
Command Prompt., Inc
 
pg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLpg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQL
Command Prompt., Inc
 
Not Just UNIQUE: Generalized Index Constraints
Not Just UNIQUE: Generalized Index ConstraintsNot Just UNIQUE: Generalized Index Constraints
Not Just UNIQUE: Generalized Index Constraints
Command Prompt., Inc
 
Implementing the Future of PostgreSQL Clustering with Tungsten
Implementing the Future of PostgreSQL Clustering with TungstenImplementing the Future of PostgreSQL Clustering with Tungsten
Implementing the Future of PostgreSQL Clustering with Tungsten
Command Prompt., Inc
 
Elephant Roads: a tour of Postgres forks
Elephant Roads: a tour of Postgres forksElephant Roads: a tour of Postgres forks
Elephant Roads: a tour of Postgres forks
Command Prompt., Inc
 
configuring a warm standby, the easy way
configuring a warm standby, the easy wayconfiguring a warm standby, the easy way
configuring a warm standby, the easy way
Command Prompt., Inc
 
Bucardo
BucardoBucardo
Bucardo
Command Prompt., Inc
 
Basic Query Tuning Primer
Basic Query Tuning PrimerBasic Query Tuning Primer
Basic Query Tuning Primer
Command Prompt., Inc
 
A Practical Multi-Tenant Cluster
A Practical Multi-Tenant ClusterA Practical Multi-Tenant Cluster
A Practical Multi-Tenant Cluster
Command Prompt., Inc
 
5 Steps to PostgreSQL Performance
5 Steps to PostgreSQL Performance5 Steps to PostgreSQL Performance
5 Steps to PostgreSQL Performance
Command Prompt., Inc
 
Normalization: A Workshop for Everybody Pt. 2
Normalization: A Workshop for Everybody Pt. 2Normalization: A Workshop for Everybody Pt. 2
Normalization: A Workshop for Everybody Pt. 2
Command Prompt., Inc
 
Normalization: A Workshop for Everybody Pt. 1
Normalization: A Workshop for Everybody Pt. 1Normalization: A Workshop for Everybody Pt. 1
Normalization: A Workshop for Everybody Pt. 1
Command Prompt., Inc
 
Howdah - An Application using Pylons, PostgreSQL, Simpycity and Exceptable
Howdah - An Application using Pylons, PostgreSQL, Simpycity and ExceptableHowdah - An Application using Pylons, PostgreSQL, Simpycity and Exceptable
Howdah - An Application using Pylons, PostgreSQL, Simpycity and Exceptable
Command Prompt., Inc
 
Mastering PostgreSQL Administration
Mastering PostgreSQL AdministrationMastering PostgreSQL Administration
Mastering PostgreSQL Administration
Command Prompt., Inc
 
Replication using PostgreSQL Replicator
Replication using PostgreSQL ReplicatorReplication using PostgreSQL Replicator
Replication using PostgreSQL Replicator
Command Prompt., Inc
 
Python utilities for data presentation
Python utilities for data presentationPython utilities for data presentation
Python utilities for data presentation
Command Prompt., Inc
 
PostgreSQL, Extensible to the Nth Degree: Functions, Languages, Types, Rules,...
PostgreSQL, Extensible to the Nth Degree: Functions, Languages, Types, Rules,...PostgreSQL, Extensible to the Nth Degree: Functions, Languages, Types, Rules,...
PostgreSQL, Extensible to the Nth Degree: Functions, Languages, Types, Rules,...
Command Prompt., Inc
 
pg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLpg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQL
Command Prompt., Inc
 
Not Just UNIQUE: Generalized Index Constraints
Not Just UNIQUE: Generalized Index ConstraintsNot Just UNIQUE: Generalized Index Constraints
Not Just UNIQUE: Generalized Index Constraints
Command Prompt., Inc
 
Implementing the Future of PostgreSQL Clustering with Tungsten
Implementing the Future of PostgreSQL Clustering with TungstenImplementing the Future of PostgreSQL Clustering with Tungsten
Implementing the Future of PostgreSQL Clustering with Tungsten
Command Prompt., Inc
 
Elephant Roads: a tour of Postgres forks
Elephant Roads: a tour of Postgres forksElephant Roads: a tour of Postgres forks
Elephant Roads: a tour of Postgres forks
Command Prompt., Inc
 
configuring a warm standby, the easy way
configuring a warm standby, the easy wayconfiguring a warm standby, the easy way
configuring a warm standby, the easy way
Command Prompt., Inc
 
Normalization: A Workshop for Everybody Pt. 2
Normalization: A Workshop for Everybody Pt. 2Normalization: A Workshop for Everybody Pt. 2
Normalization: A Workshop for Everybody Pt. 2
Command Prompt., Inc
 
Normalization: A Workshop for Everybody Pt. 1
Normalization: A Workshop for Everybody Pt. 1Normalization: A Workshop for Everybody Pt. 1
Normalization: A Workshop for Everybody Pt. 1
Command Prompt., Inc
 
Ad

Building Grails applications with PostgreSQL

  • 1. Building Grails Applications with PostgreSQL Brent Baxter and Ken Rimple PostgreSQL East - March 25, 2010 Tuesday, March 30, 2010
  • 2. About Brent and Ken • Brent Baxter: [email protected] ‣ Consultant and Applications Architect ‣ Grails, Java, and Spring developer • Ken Rimple: [email protected] ‣ Head of Education Services ‣ Host, Chariot TechCast: http://techcast.chariotsolutions.com PostgreSQL East - March 25, 2010 Tuesday, March 30, 2010
  • 3. About Chariot Solutions • Java and Open Source solutions provider • Chariot Solutions Education Services ‣ Groovy and Grails training and mentoring • Chariot Solutions Consulting ‣ Development and consulting services • http://www.chariotsolutions.com PostgreSQL East - March 25, 2010 Tuesday, March 30, 2010
  • 4. Goals • Provide a basic overview of the Grails framework - with a dash of Groovy • Review some of the features of Grails Object Relational Modeling (GORM) • Demonstrate Grails with PostgreSQL PostgreSQL East - March 25, 2010 Tuesday, March 30, 2010
  • 5. Introduction to Groovy PostgreSQL East - March 25, 2010 Tuesday, March 30, 2010
  • 6. Groovy • A dynamic language built for the Java Virtual Machine ‣ Compiles to native ByteCode ‣ Can inherit Groovy classes from Java classes (and vice versa) ‣ Native access to any Java library PostgreSQL East - March 25, 2010 Tuesday, March 30, 2010
  • 7. Benefits of Groovy • Adds "Convention over Configuration" ‣ Groovy beans are VERY simple ‣ Assumes methods are public, member variables are private ‣ Constructors not required ‣ Easy collections – Use the [ ] syntax for lists and maps PostgreSQL East - March 25, 2010 Tuesday, March 30, 2010
  • 8. A Sampling of Groovy APIs • xml – Powerful XML • builders – a set of Parsing, Creation repetitive building tasks can be automated using various • gsql – Simplified JDBC API Groovy Builders • Groovy Testing– simple • Swing – the Groovy testing API, mocking with SwingBuilder makes UI closures, etc... easy. Also Griffon is a Groovy-based MVC • Collections – lists, maps framework for Swing (like Grails for Web) and ranges PostgreSQL East - March 25, 2010 Tuesday, March 30, 2010
  • 9. Java Person Class public class Person { private String firstName; private String lastName; private Date birthDate; public Person(String firstName, String lastName, Date birthDate) { ... } public void setFirstName() { ... } public String getFirstName() { ... } // etc... } PostgreSQL East - March 25, 2010 Tuesday, March 30, 2010
  • 10. Groovy Person Class class Person { String lastName String firstName Date birthDate } PostgreSQL East - March 25, 2010 Tuesday, March 30, 2010
  • 11. Constructors and Lists // Groovy provides constructors for free def bob = new Person(firstName:'Bob', lastName:'Smith') def sue = new Person(firstName:'Sue', lastName:'Jones', birthDate:new Date('8/12/1974')) // ArrayLists are simple def persons = [ new Person(firstName:‘Bob’), new Person(firstName:‘Sue’)] persons += new Person(firstName:‘John’) PostgreSQL East - March 25, 2010 Tuesday, March 30, 2010
  • 12. Groovy SQL Support // Using JDBC def sql = Sql.newInstance(url, usr, pwd, driver) sql.execute(“insert into table values ($foo, $bar)”) sql.execute(“insert into table values (?,?)”, [a,b]) sql.eachRow(“select * from USER”) {println it.name} def list = sql.rows(“select * from USER”) PostgreSQL East - March 25, 2010 Tuesday, March 30, 2010
  • 13. Introduction to Grails PostgreSQL East - March 25, 2010 Tuesday, March 30, 2010
  • 14. Grails Framework • A web application framework ‣ Three-tiered Model View Controller (MVC) • Convention based ‣ Sensible default configuration or use any of a number of simple DSLs • Extendable with a rich set of plug-ins PostgreSQL East - March 25, 2010 Tuesday, March 30, 2010
  • 15. Grails Is Groovy • Leverages the Groovy programing language ‣ Groovy Services and Beans • Configuration DSLs ‣ Logging, data source configuration, dependency resolution, ... • Web tier Groovy Server Pages (GSP) PostgreSQL East - March 25, 2010 Tuesday, March 30, 2010
  • 16. Grails Is Java • Framework backed by best of breed industry standards ‣ Spring, Hibernate, SiteMesh, Web Flow, etc. • Leverage any Java library, access from Groovy or Java classes • Can be deployed as a Java web application (WAR) to any Servlet container PostgreSQL East - March 25, 2010 Tuesday, March 30, 2010
  • 17. Grails Technology Stack Grails Standard SiteMesh Spring Hibernate Groovy Libraries Java API Java Platform (JVM) PostgreSQL East - March 25, 2010 Tuesday, March 30, 2010
  • 18. Key Grails Components • Domain Class - A class representing an object in your domain (database table) • Controller - A class that operates on URLs submitted to the web site • View - A Groovy Server Page (GSP) designed to render the content based on a specific request PostgreSQL East - March 25, 2010 Tuesday, March 30, 2010
  • 19. Domain Driven Design with Grails • Focus on the complexities of the domain first • Create domain objects and their relationships first • Dynamically 'scaffold' controllers and views for each domain class, validate domain objects and relationships • When ready, finish by generating or coding all views, controllers, and tests PostgreSQL East - March 25, 2010 Tuesday, March 30, 2010
  • 20. Grails Scaffolding • Dynamically generated views based on default templates • No need to define a page before completing the data model // Domain // Dynamic Scaffold Controller class Person { class PersonController { String firstName def scaffold = true String lastName } Date birthDate } PostgreSQL East - March 25, 2010 Tuesday, March 30, 2010
  • 21. More than a web framework... • Eases development of every tier ‣ Integrated Groovy build system ‣ Integrated Groovy unit and integration test mechanism ‣ Simple ORM based on Hibernate ‣ Extensible plug-in system built on Spring ‣ Also simplifies Web MVC PostgreSQL East - March 25, 2010 Tuesday, March 30, 2010
  • 22. Grails Object Relational Mapping (GORM) PostgreSQL East - March 25, 2010 Tuesday, March 30, 2010
  • 23. GORM • Grails Object Relational Mapping API ‣ Uses domain classes written in Groovy ‣ Injects methods into domain classes for load, save, update, and query data ‣ Backed by Hibernate and Spring ‣ Write Hibernate objects without all of the messy XML! PostgreSQL East - March 25, 2010 Tuesday, March 30, 2010
  • 24. GORM Benefits • Write your domain classes as POGOs • Define validation via constraints • Define relationships via simple belongsTo, hasMany mappings • Easy to test framework, can use grails console or grails shell, even integration tests • Finders make it easy to locate data PostgreSQL East - March 25, 2010 Tuesday, March 30, 2010
  • 25. Grails Domain Classes • Created with create-domain-class • Simple Groovy Beans ‣ Each member variable represents a column in a table ‣ Implied version, primary key fields ‣ Can define relationships with other domains, validation constraints PostgreSQL East - March 25, 2010 Tuesday, March 30, 2010
  • 26. Connecting to PostgreSQL • Grails defines database connections for various environments (Development, Test, Production) • Steps to configure your database ‣ Install your database driver ‣ Modify grails-app/config/DataSource.groovy ‣ Boot grails with grails run-app PostgreSQL East - March 25, 2010 Tuesday, March 30, 2010
  • 27. Defining Constraints class Customer { • Checked automatically static constraints = { when saved firstName(maxLength: 15, blank: false) lastName(maxLength: 20, blank: false) or when registrationDate(nullable: false) validate() is preferredCustomer(default: true) called awardsBalance(range: 0.0..5000.0) } String firstName • Tip: scaffold String lastName configuration Date registrationDate Boolean preferredCustomer follows BigDecimal awardsBalance constraint } order for field order PostgreSQL East - March 25, 2010 Tuesday, March 30, 2010
  • 28. Entity Relationships • Grails supports all Hibernate relation mappings ‣ One to One ‣ One to Many ‣ Many to Many ‣ Parent/Child (Inheritence) PostgreSQL East - March 25, 2010 Tuesday, March 30, 2010
  • 29. One to many relationship • Customer 'owns' accounts (cascade deletes, updates, saves) class Customer { class Account { String firstName static belongsTo = String lastName [customer:Customer] ... String accountNumber static hasMany = [accounts:Account] } } // arbitrary but working example... flush for testing only... def customer = new Customer(firstName: "Dude", lastName: "WheresMyCar") def account = new Account(accountNumber:"1234", customer:customer) customer.accounts = [account] def result = customer.save(flush:true) def account2 = Account.findById(account.id) println account2.customer def customer2 = Customer.findById(customer.id) println customer2.accounts PostgreSQL East - March 25, 2010 Tuesday, March 30, 2010
  • 30. Physical DB Settings - mapping • Changing the table, versioning on/off, column mappings, indexing, multi-column-index, etc... class Person { String firstName String address static mapping = {    table 'people'    version false    id column:'person_id'    firstName column:'First_Name', index:'Name_Idx'    address column:'Address', index:'Name_Idx, Address_Index' } } PostgreSQL East - March 25, 2010 Tuesday, March 30, 2010
  • 31. Stored Procedures • Several approaches ‣ Spring's JdbcTemplate ‣ Spring's StoredProcedure class ‣ Spring's SqlFunction ‣ Groovy SQL • Demonstration PostgreSQL East - March 25, 2010 Tuesday, March 30, 2010
  • 32. Where to find the code • Hit our GitHub repository (you can just ask to download the files) • GitHub repo for our samples ‣ github.com/krimple/Grails-Demos- PostgreSQL-East-2010.git PostgreSQL East - March 25, 2010 Tuesday, March 30, 2010
  • 33. Groovy and Grails Resources • Grails Web Site ‣ http://www.grails.org • Grails User Email List ‣ http://n4.nabble.com/Grails-f1312388.html • Groovy Web Site ‣ http://groovy.codehaus.org/ PostgreSQL East - March 25, 2010 Tuesday, March 30, 2010
  • 34. Free InfoQ E-Book • Getting Started with Grails, Second Edition ‣ Scott Davis ‣ Jason Rudolph • http://www.infoq.com/ minibooks/grails-getting- started PostgreSQL East - March 25, 2010 Tuesday, March 30, 2010
  • 35. Regional User Groups • Philadelphia Groovy and Grails User Group ‣ http://phillygroovy.org ‣ Meet-up April 8 as part of Philly ETE • Philadelphia Spring User Group ‣ http://phillyspring.ning.com/ PostgreSQL East - March 25, 2010 Tuesday, March 30, 2010
  • 36. Thank you! Questions ... ? PostgreSQL East - March 25, 2010 Tuesday, March 30, 2010