SlideShare a Scribd company logo
1 of 16
Grails - Domain Classes
Hiten Pratap Singh
hiten@nexthoughts.com
https://github.com/hitenpratap
Domain Classes
• Object oriented (OO) applications involve a domain model representing the
business entities that the application deals with.
• Domain classes has properties associated with them which map to a
database in order to persist instances of those classes.
• Domain class create : grails create-domain-class <<class_name>>
Persisting Fields to the Database
• All the fields in a domain class are persisted to the database.
• Each field in the class will map to a column in the database.
Validations
• Grails allows you to apply constraints to a domain class that can then be
used to validate a domain class instance.
• Constraints are applied using a "constraints" closure.
• To validate a domain class you can call the "validate()" method on an
instance.
Example
class User {
String login
String password
String email
Date age
static constraints={
login(size:5..15,blank:false,unique:true)
password(size:5..15,blank:false)
email(email:true,blank:false)
age(min:new Date(),nullable:false)
}}
Validating Constraints
def user = new User(params)
if(user.validate()){
//do something
}else{
user.errors.allErrors.each{
Println it
}
}
CustomValidators
class User {
static constraints = {
password(unique:true, length:5..15,
validator{val, obj >
if(val?.equalsIgnoreCase(obj.firstName)){
return false
}
})}}
Transient Properties
• Transient properties are never written to the database.
• Every property in a domain class is persistent and required.
• They don't have a corresponding column in the database.
Example
• class Company {
BigDecimal cash
BigDecimal receivables
BigDecimal getNetWorth() {
cash + receivables
}
static transients = ['netWorth']
}
Custom Mapping
class Person {
String firstName
String lastName
Integer age
static mapping = {
id column:'person_id'
firstName column:'person_first_name'
lastName column:'person_last_name'
age column:'person_age'
version false
}
}
Relationships
• Every table should have at least one relationship to another table.
• The types of relationships that Grails supports are:
• One-to-one
• One-to-many
• Many-to-one
• Many-to-many
One-to-One Relationship
class Car {
Engine engine
}
class Engine {
static belongsTo = [car:Car]
}
One-to-many relationships
class Artist {
String name
static hasMany = [albums:Album]
}
Many-to-many relationships
class Book {
static belongsTo = Author
static hasMany = [authors:Author]
}
class Author {
static hasMany = [books:Book]
}
Questions?
Hiten Pratap Singh
hiten@nexthoughts.com
https://github.com/hitenpratap

More Related Content

Viewers also liked (20)

Gorm
GormGorm
Gorm
 
Jmh
JmhJmh
Jmh
 
Apache tika
Apache tikaApache tika
Apache tika
 
Bootcamp linux commands
Bootcamp linux commandsBootcamp linux commands
Bootcamp linux commands
 
G pars
G parsG pars
G pars
 
Grails custom tag lib
Grails custom tag libGrails custom tag lib
Grails custom tag lib
 
Grails internationalization-160524154831
Grails internationalization-160524154831Grails internationalization-160524154831
Grails internationalization-160524154831
 
Groovy intro
Groovy introGroovy intro
Groovy intro
 
Groovy
GroovyGroovy
Groovy
 
Meta Programming in Groovy
Meta Programming in GroovyMeta Programming in Groovy
Meta Programming in Groovy
 
Docker
DockerDocker
Docker
 
Introduction to mongo db
Introduction to mongo dbIntroduction to mongo db
Introduction to mongo db
 
Twilio
TwilioTwilio
Twilio
 
Spring boot
Spring bootSpring boot
Spring boot
 
Unit test-using-spock in Grails
Unit test-using-spock in GrailsUnit test-using-spock in Grails
Unit test-using-spock in Grails
 
MetaProgramming with Groovy
MetaProgramming with GroovyMetaProgramming with Groovy
MetaProgramming with Groovy
 
Actors model in gpars
Actors model in gparsActors model in gpars
Actors model in gpars
 
Java reflection
Java reflectionJava reflection
Java reflection
 
Grails Controllers
Grails ControllersGrails Controllers
Grails Controllers
 
Grails services
Grails servicesGrails services
Grails services
 

Similar to Grails domain classes

Advanced Design Patterns for Amazon DynamoDB - Workshop (DAT404-R1) - AWS re:...
Advanced Design Patterns for Amazon DynamoDB - Workshop (DAT404-R1) - AWS re:...Advanced Design Patterns for Amazon DynamoDB - Workshop (DAT404-R1) - AWS re:...
Advanced Design Patterns for Amazon DynamoDB - Workshop (DAT404-R1) - AWS re:...Amazon Web Services
 
Object Oriented Programming C#
Object Oriented Programming C#Object Oriented Programming C#
Object Oriented Programming C#Muhammad Younis
 
[AWS Innovate 온라인 컨퍼런스] 간단한 Python 코드만으로 높은 성능의 기계 학습 모델 만들기 - 김무현, AWS Sr.데이...
[AWS Innovate 온라인 컨퍼런스] 간단한 Python 코드만으로 높은 성능의 기계 학습 모델 만들기 - 김무현, AWS Sr.데이...[AWS Innovate 온라인 컨퍼런스] 간단한 Python 코드만으로 높은 성능의 기계 학습 모델 만들기 - 김무현, AWS Sr.데이...
[AWS Innovate 온라인 컨퍼런스] 간단한 Python 코드만으로 높은 성능의 기계 학습 모델 만들기 - 김무현, AWS Sr.데이...Amazon Web Services Korea
 
Workshop on Advanced Design Patterns for Amazon DynamoDB - DAT405 - re:Invent...
Workshop on Advanced Design Patterns for Amazon DynamoDB - DAT405 - re:Invent...Workshop on Advanced Design Patterns for Amazon DynamoDB - DAT405 - re:Invent...
Workshop on Advanced Design Patterns for Amazon DynamoDB - DAT405 - re:Invent...Amazon Web Services
 
Managing Millions of Tests Using Databricks
Managing Millions of Tests Using DatabricksManaging Millions of Tests Using Databricks
Managing Millions of Tests Using DatabricksDatabricks
 
The Ring programming language version 1.10 book - Part 86 of 212
The Ring programming language version 1.10 book - Part 86 of 212The Ring programming language version 1.10 book - Part 86 of 212
The Ring programming language version 1.10 book - Part 86 of 212Mahmoud Samir Fayed
 
Vital AI MetaQL: Queries Across NoSQL, SQL, Sparql, and Spark
Vital AI MetaQL: Queries Across NoSQL, SQL, Sparql, and SparkVital AI MetaQL: Queries Across NoSQL, SQL, Sparql, and Spark
Vital AI MetaQL: Queries Across NoSQL, SQL, Sparql, and SparkVital.AI
 
Ten Tips And Tricks for Improving Your GraphQL API with AWS AppSync (MOB401) ...
Ten Tips And Tricks for Improving Your GraphQL API with AWS AppSync (MOB401) ...Ten Tips And Tricks for Improving Your GraphQL API with AWS AppSync (MOB401) ...
Ten Tips And Tricks for Improving Your GraphQL API with AWS AppSync (MOB401) ...Amazon Web Services
 
C++ Programming Class Creation Program Assignment Instructions
C++ Programming Class Creation Program Assignment InstructionsC++ Programming Class Creation Program Assignment Instructions
C++ Programming Class Creation Program Assignment InstructionsTawnaDelatorrejs
 
Inline style best practices in reactjs
Inline style best practices in reactjsInline style best practices in reactjs
Inline style best practices in reactjsBOSC Tech Labs
 
Extending Solr: Building a Cloud-like Knowledge Discovery Platform
Extending Solr: Building a Cloud-like Knowledge Discovery PlatformExtending Solr: Building a Cloud-like Knowledge Discovery Platform
Extending Solr: Building a Cloud-like Knowledge Discovery PlatformTrey Grainger
 
Managing "Big Data" Application Complexity with CloudGraph
Managing "Big Data" Application Complexity with CloudGraphManaging "Big Data" Application Complexity with CloudGraph
Managing "Big Data" Application Complexity with CloudGraphScott Cinnamond
 
Beginners overview of automated testing with Rspec
Beginners overview of automated testing with RspecBeginners overview of automated testing with Rspec
Beginners overview of automated testing with Rspecjeffrey1ross
 
Advanced A/B Testing at Wix - Aviran Mordo and Sagy Rozman, Wix.com
Advanced A/B Testing at Wix - Aviran Mordo and Sagy Rozman, Wix.comAdvanced A/B Testing at Wix - Aviran Mordo and Sagy Rozman, Wix.com
Advanced A/B Testing at Wix - Aviran Mordo and Sagy Rozman, Wix.comDevOpsDays Tel Aviv
 
Azure Enterprise Data Analyst (DP-500) Exam Dumps 2023.pdf
Azure Enterprise Data Analyst (DP-500) Exam Dumps 2023.pdfAzure Enterprise Data Analyst (DP-500) Exam Dumps 2023.pdf
Azure Enterprise Data Analyst (DP-500) Exam Dumps 2023.pdfSkillCertProExams
 
Designing and Building a Graph Database Application - Ian Robinson (Neo Techn...
Designing and Building a Graph Database Application - Ian Robinson (Neo Techn...Designing and Building a Graph Database Application - Ian Robinson (Neo Techn...
Designing and Building a Graph Database Application - Ian Robinson (Neo Techn...jaxLondonConference
 

Similar to Grails domain classes (20)

Grails domain
Grails domainGrails domain
Grails domain
 
Advanced Design Patterns for Amazon DynamoDB - Workshop (DAT404-R1) - AWS re:...
Advanced Design Patterns for Amazon DynamoDB - Workshop (DAT404-R1) - AWS re:...Advanced Design Patterns for Amazon DynamoDB - Workshop (DAT404-R1) - AWS re:...
Advanced Design Patterns for Amazon DynamoDB - Workshop (DAT404-R1) - AWS re:...
 
Object Oriented Programming C#
Object Oriented Programming C#Object Oriented Programming C#
Object Oriented Programming C#
 
[AWS Innovate 온라인 컨퍼런스] 간단한 Python 코드만으로 높은 성능의 기계 학습 모델 만들기 - 김무현, AWS Sr.데이...
[AWS Innovate 온라인 컨퍼런스] 간단한 Python 코드만으로 높은 성능의 기계 학습 모델 만들기 - 김무현, AWS Sr.데이...[AWS Innovate 온라인 컨퍼런스] 간단한 Python 코드만으로 높은 성능의 기계 학습 모델 만들기 - 김무현, AWS Sr.데이...
[AWS Innovate 온라인 컨퍼런스] 간단한 Python 코드만으로 높은 성능의 기계 학습 모델 만들기 - 김무현, AWS Sr.데이...
 
Workshop on Advanced Design Patterns for Amazon DynamoDB - DAT405 - re:Invent...
Workshop on Advanced Design Patterns for Amazon DynamoDB - DAT405 - re:Invent...Workshop on Advanced Design Patterns for Amazon DynamoDB - DAT405 - re:Invent...
Workshop on Advanced Design Patterns for Amazon DynamoDB - DAT405 - re:Invent...
 
Introduction To Grails
Introduction To GrailsIntroduction To Grails
Introduction To Grails
 
Managing Millions of Tests Using Databricks
Managing Millions of Tests Using DatabricksManaging Millions of Tests Using Databricks
Managing Millions of Tests Using Databricks
 
The Ring programming language version 1.10 book - Part 86 of 212
The Ring programming language version 1.10 book - Part 86 of 212The Ring programming language version 1.10 book - Part 86 of 212
The Ring programming language version 1.10 book - Part 86 of 212
 
Grails basics
Grails basics Grails basics
Grails basics
 
Vital AI MetaQL: Queries Across NoSQL, SQL, Sparql, and Spark
Vital AI MetaQL: Queries Across NoSQL, SQL, Sparql, and SparkVital AI MetaQL: Queries Across NoSQL, SQL, Sparql, and Spark
Vital AI MetaQL: Queries Across NoSQL, SQL, Sparql, and Spark
 
Ten Tips And Tricks for Improving Your GraphQL API with AWS AppSync (MOB401) ...
Ten Tips And Tricks for Improving Your GraphQL API with AWS AppSync (MOB401) ...Ten Tips And Tricks for Improving Your GraphQL API with AWS AppSync (MOB401) ...
Ten Tips And Tricks for Improving Your GraphQL API with AWS AppSync (MOB401) ...
 
C++ Programming Class Creation Program Assignment Instructions
C++ Programming Class Creation Program Assignment InstructionsC++ Programming Class Creation Program Assignment Instructions
C++ Programming Class Creation Program Assignment Instructions
 
Inline style best practices in reactjs
Inline style best practices in reactjsInline style best practices in reactjs
Inline style best practices in reactjs
 
Extending Solr: Building a Cloud-like Knowledge Discovery Platform
Extending Solr: Building a Cloud-like Knowledge Discovery PlatformExtending Solr: Building a Cloud-like Knowledge Discovery Platform
Extending Solr: Building a Cloud-like Knowledge Discovery Platform
 
Managing "Big Data" Application Complexity with CloudGraph
Managing "Big Data" Application Complexity with CloudGraphManaging "Big Data" Application Complexity with CloudGraph
Managing "Big Data" Application Complexity with CloudGraph
 
Beginners overview of automated testing with Rspec
Beginners overview of automated testing with RspecBeginners overview of automated testing with Rspec
Beginners overview of automated testing with Rspec
 
Data classes in kotlin by Naveed
Data classes in kotlin by NaveedData classes in kotlin by Naveed
Data classes in kotlin by Naveed
 
Advanced A/B Testing at Wix - Aviran Mordo and Sagy Rozman, Wix.com
Advanced A/B Testing at Wix - Aviran Mordo and Sagy Rozman, Wix.comAdvanced A/B Testing at Wix - Aviran Mordo and Sagy Rozman, Wix.com
Advanced A/B Testing at Wix - Aviran Mordo and Sagy Rozman, Wix.com
 
Azure Enterprise Data Analyst (DP-500) Exam Dumps 2023.pdf
Azure Enterprise Data Analyst (DP-500) Exam Dumps 2023.pdfAzure Enterprise Data Analyst (DP-500) Exam Dumps 2023.pdf
Azure Enterprise Data Analyst (DP-500) Exam Dumps 2023.pdf
 
Designing and Building a Graph Database Application - Ian Robinson (Neo Techn...
Designing and Building a Graph Database Application - Ian Robinson (Neo Techn...Designing and Building a Graph Database Application - Ian Robinson (Neo Techn...
Designing and Building a Graph Database Application - Ian Robinson (Neo Techn...
 

More from NexThoughts Technologies (20)

Alexa skill
Alexa skillAlexa skill
Alexa skill
 
GraalVM
GraalVMGraalVM
GraalVM
 
Docker & kubernetes
Docker & kubernetesDocker & kubernetes
Docker & kubernetes
 
Apache commons
Apache commonsApache commons
Apache commons
 
HazelCast
HazelCastHazelCast
HazelCast
 
MySQL Pro
MySQL ProMySQL Pro
MySQL Pro
 
Microservice Architecture using Spring Boot with React & Redux
Microservice Architecture using Spring Boot with React & ReduxMicroservice Architecture using Spring Boot with React & Redux
Microservice Architecture using Spring Boot with React & Redux
 
Swagger
SwaggerSwagger
Swagger
 
Solid Principles
Solid PrinciplesSolid Principles
Solid Principles
 
Arango DB
Arango DBArango DB
Arango DB
 
Jython
JythonJython
Jython
 
Introduction to TypeScript
Introduction to TypeScriptIntroduction to TypeScript
Introduction to TypeScript
 
Smart Contract samples
Smart Contract samplesSmart Contract samples
Smart Contract samples
 
My Doc of geth
My Doc of gethMy Doc of geth
My Doc of geth
 
Geth important commands
Geth important commandsGeth important commands
Geth important commands
 
Ethereum genesis
Ethereum genesisEthereum genesis
Ethereum genesis
 
Ethereum
EthereumEthereum
Ethereum
 
Springboot Microservices
Springboot MicroservicesSpringboot Microservices
Springboot Microservices
 
An Introduction to Redux
An Introduction to ReduxAn Introduction to Redux
An Introduction to Redux
 
Google authentication
Google authenticationGoogle authentication
Google authentication
 

Recently uploaded

Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 

Recently uploaded (20)

Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 

Grails domain classes

  • 1. Grails - Domain Classes Hiten Pratap Singh hiten@nexthoughts.com https://github.com/hitenpratap
  • 2. Domain Classes • Object oriented (OO) applications involve a domain model representing the business entities that the application deals with. • Domain classes has properties associated with them which map to a database in order to persist instances of those classes. • Domain class create : grails create-domain-class <<class_name>>
  • 3. Persisting Fields to the Database • All the fields in a domain class are persisted to the database. • Each field in the class will map to a column in the database.
  • 4. Validations • Grails allows you to apply constraints to a domain class that can then be used to validate a domain class instance. • Constraints are applied using a "constraints" closure. • To validate a domain class you can call the "validate()" method on an instance.
  • 5. Example class User { String login String password String email Date age static constraints={ login(size:5..15,blank:false,unique:true) password(size:5..15,blank:false) email(email:true,blank:false) age(min:new Date(),nullable:false) }}
  • 6. Validating Constraints def user = new User(params) if(user.validate()){ //do something }else{ user.errors.allErrors.each{ Println it } }
  • 7. CustomValidators class User { static constraints = { password(unique:true, length:5..15, validator{val, obj > if(val?.equalsIgnoreCase(obj.firstName)){ return false } })}}
  • 8. Transient Properties • Transient properties are never written to the database. • Every property in a domain class is persistent and required. • They don't have a corresponding column in the database.
  • 9. Example • class Company { BigDecimal cash BigDecimal receivables BigDecimal getNetWorth() { cash + receivables } static transients = ['netWorth'] }
  • 10. Custom Mapping class Person { String firstName String lastName Integer age static mapping = { id column:'person_id' firstName column:'person_first_name' lastName column:'person_last_name' age column:'person_age' version false } }
  • 11. Relationships • Every table should have at least one relationship to another table. • The types of relationships that Grails supports are: • One-to-one • One-to-many • Many-to-one • Many-to-many
  • 12. One-to-One Relationship class Car { Engine engine } class Engine { static belongsTo = [car:Car] }
  • 13. One-to-many relationships class Artist { String name static hasMany = [albums:Album] }
  • 14. Many-to-many relationships class Book { static belongsTo = Author static hasMany = [authors:Author] } class Author { static hasMany = [books:Book] }