SlideShare a Scribd company logo
Overview of GORM


     Chris Richardson
 Author of POJOs in Action
 www.chrisrichardson.net
About Chris
                            Grew up in England and live in Oakland, CA
                            Over 20+ years of software development
                            experience including 12 years of Java
                            Author of POJOs in Action
                            Speaker at JavaOne, SpringOne, NFJS,
                            JavaPolis, Spring Experience, etc.
                            Chair of the eBIG Java SIG in Oakland
                            (www.ebig.org)
                            Run the Groovy/Grails meetup
                            (http://java.meetup.com/161)
                            Run a consulting and training company that
                              u    co su t g a d t a     g co pa y t at
                            helps organizations build better software faster
                            and deploy it on Amazon EC2
                            Founder of Cloud Tools, an open-source project
                            for deploying Java applications on Amazon EC2:
                            http://code.google.com/p/cloudtools
                            http://code google com/p/cloudtools
                            Founder of a startup that provides outsourced,
                            automated, and Java-centric datacenter
                            management on the cloud:
                            www.cloudfoundry.com
                                              y



                                                                      Slide 2
          Copyright (c) 2009 Chris Richardson. All rights reserved.
What’s GORM?
 GORM = Grails Object Relational Mapping
 Built
 B ilt on Hibe nate
          Hibernate
   Leverages the power of Hibernate
   But is very different - simpler, easier to use API
             y                p,
 Uses convention over configuration
   Defaults for which classes to persist
   Defaults for their O/R mapping
 Leverages the meta-object protocol
   Adds persistence methods to domain classes
         p
   No equivalent of Hibernate Session
   Avoids the need for dependency injection
   Eliminates many DAO cookie-cutter methods

                                                                           Slide 3
               Copyright (c) 2009 Chris Richardson. All rights reserved.
Database access made easy
                        y
 class Customer {
    String name
         g
 }



 Customer c = new Customer(quot;John Doequot;)
 Ct               Ct      (quot;J h D quot;)

 if (!c.save())
    fail quot;validation failed: ${c.errors}quot;

 Customer c2 = Customer.get(c.id)
                                                                                    No dependency
                                                                                       injection

 c2.delete()

 assertNull Customer.get(c.id)


 def customers = Customer findAllByName(“Fred”)
                 Customer.findAllByName( Fred )


                                                                                    Slide 4
                        Copyright (c) 2009 Chris Richardson. All rights reserved.
Relationships don’t have to be
 difficult

class Customer {
   static hasMany = [ accounts : Account]
}

class Account {
   static belongsTo = [customer: Customer]
   double balance
}


 Customer c = <…>
 Account a = new Account(…)
 c.addToAccounts(a)

 assertSame c, a.customer
 assertTrue c.accounts.contains(a)




                                                                                     Slide 5
                         Copyright (c) 2009 Chris Richardson. All rights reserved.
When the defaults aren’t right
                            g
class Customer {
   static transients = [quot;networthquot;]
                       [          ]

    static mapping = {
      id column: 'customer_id'
      table 'crc_customer'
                _
      columns {
         name column: 'customer_name'
      }
    }


    def getNetworth() { …}
    …
}




                                                                                         Slide 6
                             Copyright (c) 2009 Chris Richardson. All rights reserved.
Working with constraints
       g
class Customer {

    static constraints = {
            name(size: 5..15, blank: false)
    }

    String name

}




             Checked by the UI
             Checked by save()
             Used by GORM to generate schema constraints




                                                                                      Slide 7
                          Copyright (c) 2009 Chris Richardson. All rights reserved.
More on dynamic finders
         y
 Rich query language
   Various methods: fi dB () fi dAllB ()
   Vi          th d findBy…(), findAllBy…(),
   countBy…()
   Various operators: e.g
   findAllByFirstNameAndLastName(…),
   findAllByBalanceLessThan(…),
   findAllByStatusIsNotNull()
           y               ()
 BUT:
   Limited to single class/table, i.e. no joins
   Lack of encapsulation – the name of the
   finder reflects the implementation – not the
   meaning

                                                                          Slide 8
              Copyright (c) 2009 Chris Richardson. All rights reserved.
When dynamic finders are
   insufficient

                                                                              HQL

List accounts = Account.findAll(“from Account where balance < ?”, [threshold])




  def c = Account.createCriteria()
  def results = c.list {
     lt( balance
     lt(“balance”, threshold)
  }




                                                                                        Slide 9
                            Copyright (c) 2009 Chris Richardson. All rights reserved.
Mapping with XML or annotations
  pp g
 Using .hbm.xml files
   Create grails-
   app/conf/hibernate/hibernate.cfg.xml
   Define .hbm.xml mapping files
   D fi    hb     l      i  fil
   Map either Groovy or Java classes
 Using JPA annotations
 Ui            t ti
   Annotate Java classes
   Create hib
   C      hibernate.cfg.xml
                     f    l
 You can still use the dynamically
 defined
 d fi d GORM methods i G
                    th d in Groovy
                                                                         Slide 10
             Copyright (c) 2009 Chris Richardson. All rights reserved.
Under the covers
 Creates DataSource specified in grails-
 app/config/DataSource.groovy
 Creates Hibernate SessionFactory
 Use ExpandoMetaClass mechanism
   Add persistence methods, e.g.
   domainClass.metaClass.'static'.get = {…}
   Adds methodMissing() to handle dynamic
   finders
   fi d
   These methods have a reference to the
   SessionFactory

                                                                        Slide 11
            Copyright (c) 2009 Chris Richardson. All rights reserved.
GORM is great but …
        g
 GORM does not support multiple
 DataSources
 Lack of SOC
   Data access logic is scattered around the
   application rather than being
   encapsulated by DAOs
 CoC-based mapping works best for
 new databases
 Disadvantages of programming in a
 dynamic language
                                                                         Slide 12
             Copyright (c) 2009 Chris Richardson. All rights reserved.
Further reading
              g
 My ACM Queue article:
   http://queue.acm.org/detail.cfm?id=1394140




                                                                           Slide 13
               Copyright (c) 2009 Chris Richardson. All rights reserved.

More Related Content

What's hot

What's hot (20)

IaC on AWS Cloud
IaC on AWS CloudIaC on AWS Cloud
IaC on AWS Cloud
 
AWS CloudFormation Tutorial | AWS CloudFormation Demo | AWS Tutorial | AWS Tr...
AWS CloudFormation Tutorial | AWS CloudFormation Demo | AWS Tutorial | AWS Tr...AWS CloudFormation Tutorial | AWS CloudFormation Demo | AWS Tutorial | AWS Tr...
AWS CloudFormation Tutorial | AWS CloudFormation Demo | AWS Tutorial | AWS Tr...
 
All the Ops: DataOps with GitOps for Streaming data on Kafka and Kubernetes
All the Ops: DataOps with GitOps for Streaming data on Kafka and KubernetesAll the Ops: DataOps with GitOps for Streaming data on Kafka and Kubernetes
All the Ops: DataOps with GitOps for Streaming data on Kafka and Kubernetes
 
Asgard, the Grails App that Deploys Netflix to the Cloud
Asgard, the Grails App that Deploys Netflix to the CloudAsgard, the Grails App that Deploys Netflix to the Cloud
Asgard, the Grails App that Deploys Netflix to the Cloud
 
AWS Summit Santa Slara 2019 Mar ECS
AWS Summit Santa Slara 2019 Mar ECSAWS Summit Santa Slara 2019 Mar ECS
AWS Summit Santa Slara 2019 Mar ECS
 
Getting Started with Kubernetes on AWS
Getting Started with Kubernetes on AWSGetting Started with Kubernetes on AWS
Getting Started with Kubernetes on AWS
 
From Docker Straight to AWS
From Docker Straight to AWSFrom Docker Straight to AWS
From Docker Straight to AWS
 
Announcing AWS Batch - Run Batch Jobs At Scale - December 2016 Monthly Webina...
Announcing AWS Batch - Run Batch Jobs At Scale - December 2016 Monthly Webina...Announcing AWS Batch - Run Batch Jobs At Scale - December 2016 Monthly Webina...
Announcing AWS Batch - Run Batch Jobs At Scale - December 2016 Monthly Webina...
 
TDC2017 | São Paulo - Trilha Cloud Computing How we figured out we had a SRE ...
TDC2017 | São Paulo - Trilha Cloud Computing How we figured out we had a SRE ...TDC2017 | São Paulo - Trilha Cloud Computing How we figured out we had a SRE ...
TDC2017 | São Paulo - Trilha Cloud Computing How we figured out we had a SRE ...
 
TDC2017 | São Paulo - Trilha Cloud Computing How we figured out we had a SRE ...
TDC2017 | São Paulo - Trilha Cloud Computing How we figured out we had a SRE ...TDC2017 | São Paulo - Trilha Cloud Computing How we figured out we had a SRE ...
TDC2017 | São Paulo - Trilha Cloud Computing How we figured out we had a SRE ...
 
AWS CDK introduction
AWS CDK introductionAWS CDK introduction
AWS CDK introduction
 
Avoid the chaos - Handling 100+ OSGi Components - Balázs Zsoldos
Avoid the chaos - Handling 100+ OSGi Components - Balázs ZsoldosAvoid the chaos - Handling 100+ OSGi Components - Balázs Zsoldos
Avoid the chaos - Handling 100+ OSGi Components - Balázs Zsoldos
 
An MPI-IO Cloud Cluster Bioinformatics Summer Project (BDT205) | AWS re:Inven...
An MPI-IO Cloud Cluster Bioinformatics Summer Project (BDT205) | AWS re:Inven...An MPI-IO Cloud Cluster Bioinformatics Summer Project (BDT205) | AWS re:Inven...
An MPI-IO Cloud Cluster Bioinformatics Summer Project (BDT205) | AWS re:Inven...
 
Batch Processing with Amazon EC2 Container Service
Batch Processing with Amazon EC2 Container ServiceBatch Processing with Amazon EC2 Container Service
Batch Processing with Amazon EC2 Container Service
 
Deep Learning for Developers (Advanced Workshop)
Deep Learning for Developers (Advanced Workshop)Deep Learning for Developers (Advanced Workshop)
Deep Learning for Developers (Advanced Workshop)
 
Machine learning in the physical world by Kip Larson from AWS IoT
Machine learning in the physical world by  Kip Larson from AWS IoTMachine learning in the physical world by  Kip Larson from AWS IoT
Machine learning in the physical world by Kip Larson from AWS IoT
 
IaC로 AWS인프라 관리하기 - 이진성 (AUSG) :: AWS Community Day Online 2021
IaC로 AWS인프라 관리하기 - 이진성 (AUSG) :: AWS Community Day Online 2021IaC로 AWS인프라 관리하기 - 이진성 (AUSG) :: AWS Community Day Online 2021
IaC로 AWS인프라 관리하기 - 이진성 (AUSG) :: AWS Community Day Online 2021
 
Write less (code) and build more with serverless
Write less (code) and build more with serverlessWrite less (code) and build more with serverless
Write less (code) and build more with serverless
 
The Good, the Bad and the Ugly of Migrating Hundreds of Legacy Applications ...
 The Good, the Bad and the Ugly of Migrating Hundreds of Legacy Applications ... The Good, the Bad and the Ugly of Migrating Hundreds of Legacy Applications ...
The Good, the Bad and the Ugly of Migrating Hundreds of Legacy Applications ...
 
Serverless Architectural Patterns 
and Best Practices - Madhu Shekar - AWS
Serverless Architectural Patterns 
and Best Practices - Madhu Shekar - AWSServerless Architectural Patterns 
and Best Practices - Madhu Shekar - AWS
Serverless Architectural Patterns 
and Best Practices - Madhu Shekar - AWS
 

Similar to Overview of Grails Object Relational Mapping (GORM)

Googleappengineintro 110410190620-phpapp01
Googleappengineintro 110410190620-phpapp01Googleappengineintro 110410190620-phpapp01
Googleappengineintro 110410190620-phpapp01
Tony Frame
 

Similar to Overview of Grails Object Relational Mapping (GORM) (20)

CommunityOneEast 09 - Dynamic Languages: the next big thing for the JVM or an...
CommunityOneEast 09 - Dynamic Languages: the next big thing for the JVM or an...CommunityOneEast 09 - Dynamic Languages: the next big thing for the JVM or an...
CommunityOneEast 09 - Dynamic Languages: the next big thing for the JVM or an...
 
Universal Declarative Services - Simon Chemouil
Universal Declarative Services - Simon ChemouilUniversal Declarative Services - Simon Chemouil
Universal Declarative Services - Simon Chemouil
 
The curious Life of JavaScript - Talk at SI-SE 2015
The curious Life of JavaScript - Talk at SI-SE 2015The curious Life of JavaScript - Talk at SI-SE 2015
The curious Life of JavaScript - Talk at SI-SE 2015
 
Building Rich Domain Models
Building Rich Domain ModelsBuilding Rich Domain Models
Building Rich Domain Models
 
a Running Tour of Cloud Foundry
a Running Tour of Cloud Foundrya Running Tour of Cloud Foundry
a Running Tour of Cloud Foundry
 
Drone Continuous Integration
Drone Continuous IntegrationDrone Continuous Integration
Drone Continuous Integration
 
Introduction To Grails
Introduction To GrailsIntroduction To Grails
Introduction To Grails
 
Running Serverless at The Edge (CTD302) - AWS re:Invent 2018
Running Serverless at The Edge (CTD302) - AWS re:Invent 2018Running Serverless at The Edge (CTD302) - AWS re:Invent 2018
Running Serverless at The Edge (CTD302) - AWS re:Invent 2018
 
CommunityOneEast 09 - Running Java On Amazon EC2
CommunityOneEast 09 - Running Java On Amazon EC2CommunityOneEast 09 - Running Java On Amazon EC2
CommunityOneEast 09 - Running Java On Amazon EC2
 
Scripting Oracle Develop 2007
Scripting Oracle Develop 2007Scripting Oracle Develop 2007
Scripting Oracle Develop 2007
 
Framework engineering JCO 2011
Framework engineering JCO 2011Framework engineering JCO 2011
Framework engineering JCO 2011
 
Breaking the Monolith road to containers.pdf
Breaking the Monolith road to containers.pdfBreaking the Monolith road to containers.pdf
Breaking the Monolith road to containers.pdf
 
#MBLTdev: Разработка первоклассных SDK для Android (Twitter)
#MBLTdev: Разработка первоклассных SDK для Android (Twitter)#MBLTdev: Разработка первоклассных SDK для Android (Twitter)
#MBLTdev: Разработка первоклассных SDK для Android (Twitter)
 
02 c++g3 d
02 c++g3 d02 c++g3 d
02 c++g3 d
 
Advanced Container Automation, Security, and Monitoring - AWS Summit Sydney 2018
Advanced Container Automation, Security, and Monitoring - AWS Summit Sydney 2018Advanced Container Automation, Security, and Monitoring - AWS Summit Sydney 2018
Advanced Container Automation, Security, and Monitoring - AWS Summit Sydney 2018
 
New and cool in OSGi R7 - David Bosschaert & Carsten Ziegeler
New and cool in OSGi R7 - David Bosschaert & Carsten ZiegelerNew and cool in OSGi R7 - David Bosschaert & Carsten Ziegeler
New and cool in OSGi R7 - David Bosschaert & Carsten Ziegeler
 
Single Page JavaScript WebApps... A Gradle Story
Single Page JavaScript WebApps... A Gradle StorySingle Page JavaScript WebApps... A Gradle Story
Single Page JavaScript WebApps... A Gradle Story
 
Googleappengineintro 110410190620-phpapp01
Googleappengineintro 110410190620-phpapp01Googleappengineintro 110410190620-phpapp01
Googleappengineintro 110410190620-phpapp01
 
High performance web programming with C++14
High performance web programming with C++14High performance web programming with C++14
High performance web programming with C++14
 
Developer Android Tools
Developer Android ToolsDeveloper Android Tools
Developer Android Tools
 

More from Chris Richardson

More from Chris Richardson (20)

The microservice architecture: what, why, when and how?
The microservice architecture: what, why, when and how?The microservice architecture: what, why, when and how?
The microservice architecture: what, why, when and how?
 
More the merrier: a microservices anti-pattern
More the merrier: a microservices anti-patternMore the merrier: a microservices anti-pattern
More the merrier: a microservices anti-pattern
 
YOW London - Considering Migrating a Monolith to Microservices? A Dark Energy...
YOW London - Considering Migrating a Monolith to Microservices? A Dark Energy...YOW London - Considering Migrating a Monolith to Microservices? A Dark Energy...
YOW London - Considering Migrating a Monolith to Microservices? A Dark Energy...
 
Dark Energy, Dark Matter and the Microservices Patterns?!
Dark Energy, Dark Matter and the Microservices Patterns?!Dark Energy, Dark Matter and the Microservices Patterns?!
Dark Energy, Dark Matter and the Microservices Patterns?!
 
Dark energy, dark matter and microservice architecture collaboration patterns
Dark energy, dark matter and microservice architecture collaboration patternsDark energy, dark matter and microservice architecture collaboration patterns
Dark energy, dark matter and microservice architecture collaboration patterns
 
Scenarios_and_Architecture_SkillsMatter_April_2022.pdf
Scenarios_and_Architecture_SkillsMatter_April_2022.pdfScenarios_and_Architecture_SkillsMatter_April_2022.pdf
Scenarios_and_Architecture_SkillsMatter_April_2022.pdf
 
Using patterns and pattern languages to make better architectural decisions
Using patterns and pattern languages to make better architectural decisions Using patterns and pattern languages to make better architectural decisions
Using patterns and pattern languages to make better architectural decisions
 
iSAQB gathering 2021 keynote - Architectural patterns for rapid, reliable, fr...
iSAQB gathering 2021 keynote - Architectural patterns for rapid, reliable, fr...iSAQB gathering 2021 keynote - Architectural patterns for rapid, reliable, fr...
iSAQB gathering 2021 keynote - Architectural patterns for rapid, reliable, fr...
 
Events to the rescue: solving distributed data problems in a microservice arc...
Events to the rescue: solving distributed data problems in a microservice arc...Events to the rescue: solving distributed data problems in a microservice arc...
Events to the rescue: solving distributed data problems in a microservice arc...
 
A pattern language for microservices - June 2021
A pattern language for microservices - June 2021 A pattern language for microservices - June 2021
A pattern language for microservices - June 2021
 
QConPlus 2021: Minimizing Design Time Coupling in a Microservice Architecture
QConPlus 2021: Minimizing Design Time Coupling in a Microservice ArchitectureQConPlus 2021: Minimizing Design Time Coupling in a Microservice Architecture
QConPlus 2021: Minimizing Design Time Coupling in a Microservice Architecture
 
Mucon 2021 - Dark energy, dark matter: imperfect metaphors for designing micr...
Mucon 2021 - Dark energy, dark matter: imperfect metaphors for designing micr...Mucon 2021 - Dark energy, dark matter: imperfect metaphors for designing micr...
Mucon 2021 - Dark energy, dark matter: imperfect metaphors for designing micr...
 
Designing loosely coupled services
Designing loosely coupled servicesDesigning loosely coupled services
Designing loosely coupled services
 
Microservices - an architecture that enables DevOps (T Systems DevOps day)
Microservices - an architecture that enables DevOps (T Systems DevOps day)Microservices - an architecture that enables DevOps (T Systems DevOps day)
Microservices - an architecture that enables DevOps (T Systems DevOps day)
 
DDD SoCal: Decompose your monolith: Ten principles for refactoring a monolith...
DDD SoCal: Decompose your monolith: Ten principles for refactoring a monolith...DDD SoCal: Decompose your monolith: Ten principles for refactoring a monolith...
DDD SoCal: Decompose your monolith: Ten principles for refactoring a monolith...
 
Decompose your monolith: Six principles for refactoring a monolith to microse...
Decompose your monolith: Six principles for refactoring a monolith to microse...Decompose your monolith: Six principles for refactoring a monolith to microse...
Decompose your monolith: Six principles for refactoring a monolith to microse...
 
TDC2020 - The microservice architecture: enabling rapid, reliable, frequent a...
TDC2020 - The microservice architecture: enabling rapid, reliable, frequent a...TDC2020 - The microservice architecture: enabling rapid, reliable, frequent a...
TDC2020 - The microservice architecture: enabling rapid, reliable, frequent a...
 
Overview of the Eventuate Tram Customers and Orders application
Overview of the Eventuate Tram Customers and Orders applicationOverview of the Eventuate Tram Customers and Orders application
Overview of the Eventuate Tram Customers and Orders application
 
An overview of the Eventuate Platform
An overview of the Eventuate PlatformAn overview of the Eventuate Platform
An overview of the Eventuate Platform
 
#DevNexus202 Decompose your monolith
#DevNexus202 Decompose your monolith#DevNexus202 Decompose your monolith
#DevNexus202 Decompose your monolith
 

Recently uploaded

Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
Bhaskar Mitra
 

Recently uploaded (20)

IESVE for Early Stage Design and Planning
IESVE for Early Stage Design and PlanningIESVE for Early Stage Design and Planning
IESVE for Early Stage Design and Planning
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
 
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
 
In-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT ProfessionalsIn-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT Professionals
 
Agentic RAG What it is its types applications and implementation.pdf
Agentic RAG What it is its types applications and implementation.pdfAgentic RAG What it is its types applications and implementation.pdf
Agentic RAG What it is its types applications and implementation.pdf
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
The architecture of Generative AI for enterprises.pdf
The architecture of Generative AI for enterprises.pdfThe architecture of Generative AI for enterprises.pdf
The architecture of Generative AI for enterprises.pdf
 
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone KomSalesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
 
Optimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through ObservabilityOptimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through Observability
 
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeFree and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
 
UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1
 
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
PLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. StartupsPLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. Startups
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 

Overview of Grails Object Relational Mapping (GORM)

  • 1. Overview of GORM Chris Richardson Author of POJOs in Action www.chrisrichardson.net
  • 2. About Chris Grew up in England and live in Oakland, CA Over 20+ years of software development experience including 12 years of Java Author of POJOs in Action Speaker at JavaOne, SpringOne, NFJS, JavaPolis, Spring Experience, etc. Chair of the eBIG Java SIG in Oakland (www.ebig.org) Run the Groovy/Grails meetup (http://java.meetup.com/161) Run a consulting and training company that u co su t g a d t a g co pa y t at helps organizations build better software faster and deploy it on Amazon EC2 Founder of Cloud Tools, an open-source project for deploying Java applications on Amazon EC2: http://code.google.com/p/cloudtools http://code google com/p/cloudtools Founder of a startup that provides outsourced, automated, and Java-centric datacenter management on the cloud: www.cloudfoundry.com y Slide 2 Copyright (c) 2009 Chris Richardson. All rights reserved.
  • 3. What’s GORM? GORM = Grails Object Relational Mapping Built B ilt on Hibe nate Hibernate Leverages the power of Hibernate But is very different - simpler, easier to use API y p, Uses convention over configuration Defaults for which classes to persist Defaults for their O/R mapping Leverages the meta-object protocol Adds persistence methods to domain classes p No equivalent of Hibernate Session Avoids the need for dependency injection Eliminates many DAO cookie-cutter methods Slide 3 Copyright (c) 2009 Chris Richardson. All rights reserved.
  • 4. Database access made easy y class Customer { String name g } Customer c = new Customer(quot;John Doequot;) Ct Ct (quot;J h D quot;) if (!c.save()) fail quot;validation failed: ${c.errors}quot; Customer c2 = Customer.get(c.id) No dependency injection c2.delete() assertNull Customer.get(c.id) def customers = Customer findAllByName(“Fred”) Customer.findAllByName( Fred ) Slide 4 Copyright (c) 2009 Chris Richardson. All rights reserved.
  • 5. Relationships don’t have to be difficult class Customer { static hasMany = [ accounts : Account] } class Account { static belongsTo = [customer: Customer] double balance } Customer c = <…> Account a = new Account(…) c.addToAccounts(a) assertSame c, a.customer assertTrue c.accounts.contains(a) Slide 5 Copyright (c) 2009 Chris Richardson. All rights reserved.
  • 6. When the defaults aren’t right g class Customer { static transients = [quot;networthquot;] [ ] static mapping = { id column: 'customer_id' table 'crc_customer' _ columns { name column: 'customer_name' } } def getNetworth() { …} … } Slide 6 Copyright (c) 2009 Chris Richardson. All rights reserved.
  • 7. Working with constraints g class Customer { static constraints = { name(size: 5..15, blank: false) } String name } Checked by the UI Checked by save() Used by GORM to generate schema constraints Slide 7 Copyright (c) 2009 Chris Richardson. All rights reserved.
  • 8. More on dynamic finders y Rich query language Various methods: fi dB () fi dAllB () Vi th d findBy…(), findAllBy…(), countBy…() Various operators: e.g findAllByFirstNameAndLastName(…), findAllByBalanceLessThan(…), findAllByStatusIsNotNull() y () BUT: Limited to single class/table, i.e. no joins Lack of encapsulation – the name of the finder reflects the implementation – not the meaning Slide 8 Copyright (c) 2009 Chris Richardson. All rights reserved.
  • 9. When dynamic finders are insufficient HQL List accounts = Account.findAll(“from Account where balance < ?”, [threshold]) def c = Account.createCriteria() def results = c.list { lt( balance lt(“balance”, threshold) } Slide 9 Copyright (c) 2009 Chris Richardson. All rights reserved.
  • 10. Mapping with XML or annotations pp g Using .hbm.xml files Create grails- app/conf/hibernate/hibernate.cfg.xml Define .hbm.xml mapping files D fi hb l i fil Map either Groovy or Java classes Using JPA annotations Ui t ti Annotate Java classes Create hib C hibernate.cfg.xml f l You can still use the dynamically defined d fi d GORM methods i G th d in Groovy Slide 10 Copyright (c) 2009 Chris Richardson. All rights reserved.
  • 11. Under the covers Creates DataSource specified in grails- app/config/DataSource.groovy Creates Hibernate SessionFactory Use ExpandoMetaClass mechanism Add persistence methods, e.g. domainClass.metaClass.'static'.get = {…} Adds methodMissing() to handle dynamic finders fi d These methods have a reference to the SessionFactory Slide 11 Copyright (c) 2009 Chris Richardson. All rights reserved.
  • 12. GORM is great but … g GORM does not support multiple DataSources Lack of SOC Data access logic is scattered around the application rather than being encapsulated by DAOs CoC-based mapping works best for new databases Disadvantages of programming in a dynamic language Slide 12 Copyright (c) 2009 Chris Richardson. All rights reserved.
  • 13. Further reading g My ACM Queue article: http://queue.acm.org/detail.cfm?id=1394140 Slide 13 Copyright (c) 2009 Chris Richardson. All rights reserved.