SlideShare ist ein Scribd-Unternehmen logo
1 von 13
Downloaden Sie, um offline zu lesen
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.

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (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
 

Ähnlich wie Overview of Grails Object Relational Mapping (GORM)

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

Ähnlich wie 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
 

Mehr von Chris Richardson

Mehr von 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
 

Kürzlich hochgeladen

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Kürzlich hochgeladen (20)

Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 

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.