SlideShare a Scribd company logo
1 of 24
Download to read offline
1
Understanding Database Transactions and
Hibernate Sessions in Grails
jonas.witt@valsight.com
@jonaswitt
Jonas Witt
Berlin Groovy User Group
2017-05-11
3
GORM/Hibernate: Introduction
• Hibernate is a very powerful Java Object/Relational
Mapping (ORM) framework that accesses relational
databases via JDBC
• GORM is Grails’ default ORM and uses Hibernate as one of
its backends (others: Mongo, Neo4J, REST)
• Both combined make persistence of your application’s
domain model very convenient – but understanding the
details is essential when using the frameworks in production
4
Today’s Focus: Saving Domain Objects
• This talk will focus on saving domain objects,
i.e. the behavior of abstraction layers between your
author.save() call and (eventually) persistence
• To better understand reading domain objects, consider:
– Using Hibernate caching:
http://gorm.grails.org/6.0.x/hibernate/manual/#advancedGORMF
eatures
– “hasMany Considered Harmful” by Burt Beckwith:
https://www.youtube.com/watch?v=-nofscHeEuU
5
Hibernate Sessions
6
Hibernate: transactional write-behind
class AuthorController {
def sessionFactory
def updateName() {
Author author = Author.get(params.id)
author.name = 'Donald Knuth'
author.save()
sessionFactory.currentSession.flush()
render author as JSON
}
}
7
Hibernate: transactional
write-behind
1) By default, a controller uses a
non-transactional database
connection
2) Saving a GORM object does
not not necessarily flush the
changes to the database –
updates are batched for
better performance
3) session.flush() or save(flush:
true) forces the Hibernate
session to be flushed
Grails Controller Hibernate Session SQL Database
HTTP PUT
(start session)
getConnection() (1)
Author.get(id)
(check 1st level cache)
SELECT * FROM
author WHERE id = ?
author.name =
"Donald Knuth"
author.save() (2)
session.flush() (3)
UPDATE author SET ...
WHERE id = ?
200 OK
8
Hibernate FlushMode
1) In order to guarantee
correctness of the
returned author list,
Hibernate will flush
pending changes
(flushMode = AUTO,
default in GORM < 6.1)
FlushModes: ALWAYS,
AUTO, COMMIT, MANUAL
Grails Controller Hibernate Session SQL Database
HTTP PUT
author.name =
"Donald Knuth"
author.save()
Author.list() (1)
UPDATE author SET ...
WHERE id = ?
SELECT * FROM author
200 OK
10
Hibernate session: summary
• The Hibernate session batches updates to the underlying
database for performance reasons
• FlushMode = AUTO triggers implicit flushes when querying
the database would lead to an outdated response otherwise
• Use explicit flush()/clear() to reduce size of Hibernate session
11
Database Transactions
12
Updating entities without transactions
Problems:
• Concurrent requests will see a state
where only some of the 4 books exists
• When the action fails in between, the
DB will be left in an inconsistent state
class AuthorController {
def createDefaultBooks() {
Author author = Author.get(params.id)
List books = (1..4).collect {
new Book(author: author,
title: "The Art of Computer Programming, Vol. $it")
}
books*.save(flush: true)
render books as JSON
}
}
13
Updating entities without transactions
Grails Controller Hibernate Session SQL Database
HTTP PUT
book1.save(flush: true)
INSERT INTO books VALUES (?, ?, ?)
book2.save(flush: true)
INSERT INTO books VALUES (?, ?, ?)
render books as JSON
200 OK
14
import grails.transaction.Transactional
class AuthorController {
@Transactional
def createDefaultBooks() {
Author author = Author.get(params.id)
List books = (1..4).collect {
new Book(author: author,
title: "The Art of Computer Programming, Vol. $it")
}
books*.save(flush: true)
render books as JSON
}
}
Updating entities with transactions*
(*) Don’t do this at home!
Transactional behavior: CHECK! !
15
Updating entities with transactions*
(*) Don’t do this at home!
Grails Controller Hibernate Session Transaction SQL Database
HTTP PUT
@Transactional
START TRANSACTION
book1.save(flush: true)
INSERT INTO books VALUES (?, ?, ?)
book2.save(flush: true)
INSERT INTO books VALUES (?, ?, ?)
(end of action)
COMMIT
200 OK
16
DEMO, pt. 1
17
[https://en.wikipedia.org/wiki/Race_condition]
“Race conditions arise in software when an application
depends on the sequence or timing
of processes or threads for it to operate properly.”
“When adding a sleep() statement makes your program fail,
there is a race condition”
[Some clever programmer, somewhere]
18
DEMO, pt. 2
19
Grails Controller Hibernate Session Transaction SQL Database
HTTP PUT
@Transactional
START TRANSACTION
book1.save(flush: true)
INSERT INTO books VALUES (?, ?, ?)
book2.save(flush: true)
INSERT INTO books VALUES (?, ?, ?)
(end of action)
COMMIT
render books as JSON
200 OK
Updating entities with transactions*
(*) Don’t do this at home!
20
Updating entities with transactions*
(*) Don’t do this at home!
Grails Controller Hibernate Session Transaction SQL Database
HTTP PUT
@Transactional
START TRANSACTION
book1.save(flush: true)
INSERT INTO books VALUES (?, ?, ?)
book2.save(flush: true)
INSERT INTO books VALUES (?, ?, ?)
render books as JSON
200 OK
(end of action)
COMMIT
21
Updating
entities with
transactions*
(*) Don’t do this at home!
Grails Controller Hibernate Session Transaction SQL Database
HTTP PUT
@Transactional
START TRANSACTION
book1.save(flush: true)
INSERT INTO books VALUES (?, ?, ?)
book2.save(flush: true)
INSERT INTO books VALUES (?, ?, ?)
render books as JSON
200 OK
HTTP GET
SELECT * FROM books
WHERE id = ?
404 Not Found
(end of action)
COMMIT
22
Transactional
by default! ! ! !
class AuthorService {
def createDefaultBooks(Author author) {
List books = (1..4).collect {
new Book(author: author,
title: "The Art of Computer Programming, Vol. $it")
}
books*.save(flush: true)
return books
}
}
class AuthorController {
def authorService
def createDefaultBooks() {
Author author = Author.get(params.id)
def books = authorService.createDefaultBooks(author)
render books as JSON
}
}
23
• The Grails service
provides
@Transactional
behavior by default
• The service method
boundaries
encapsulate the
business logic, and
separate it from the
HTTP request handling
Grails Controller Service Transaction SQL Database
HTTP PUT
SELECT * FROM author WHERE id = ?
@Transactional
START TRANSACTION
INSERT INTO books VALUES (?, ?, ?)
INSERT INTO books VALUES (?, ?, ?)
(end of transactional method)
COMMIT
render books as JSON
200 OK
Updating entities with transactions: best practice
24
SQL transaction isolation
Isolation level Dirty reads
Non-repeatable
reads
Phantom reads
Read Uncommitted may occur may occur may occur
Read Committed don't occur may occur may occur
Repeatable Read don't occur don't occur may occur
Serializable don't occur don't occur don't occur
[https://en.wikipedia.org/wiki/Isolation_(database_systems)]
The default
in many
JDBC drivers
25
SQL transactions summary
• Use transactions to ensure atomic updates of related objects
• Be mindful of transaction boundaries
• Best practice:
– Let Controllers handle the HTTP request only: parse HTTP
parameters / request body, and render the HTTP response
– Services (transactional by default) should be used to manipulate
GORM objects (both light + heavy lifting)
Thank you!
jonas.witt@valsight.com
@jonaswitt
Valsight GmbH
Uhlandstr. 29
10719 Berlin

More Related Content

What's hot

Ruby on Rails Presentation
Ruby on Rails PresentationRuby on Rails Presentation
Ruby on Rails Presentationadamcookeuk
 
Collections - Maps
Collections - Maps Collections - Maps
Collections - Maps Hitesh-Java
 
Introduction to Python Celery
Introduction to Python CeleryIntroduction to Python Celery
Introduction to Python CeleryMahendra M
 
Nitro for your Grails App: how to improve performance. Greach '18
Nitro for your Grails App: how to improve performance. Greach '18Nitro for your Grails App: how to improve performance. Greach '18
Nitro for your Grails App: how to improve performance. Greach '18Alberto De Ávila Hernández
 
Introducing Async/Await
Introducing Async/AwaitIntroducing Async/Await
Introducing Async/AwaitValeri Karpov
 
Dynamic Components using Single-Page-Application Concepts in AEM/CQ
Dynamic Components using Single-Page-Application Concepts in AEM/CQDynamic Components using Single-Page-Application Concepts in AEM/CQ
Dynamic Components using Single-Page-Application Concepts in AEM/CQNetcetera
 
Percona XtraDB Cluster ( Ensure high Availability )
Percona XtraDB Cluster ( Ensure high Availability )Percona XtraDB Cluster ( Ensure high Availability )
Percona XtraDB Cluster ( Ensure high Availability )Mydbops
 
Java Server Faces (JSF) - Basics
Java Server Faces (JSF) - BasicsJava Server Faces (JSF) - Basics
Java Server Faces (JSF) - BasicsBG Java EE Course
 
The Functional Programming Triad of Map, Filter and Fold
The Functional Programming Triad of Map, Filter and FoldThe Functional Programming Triad of Map, Filter and Fold
The Functional Programming Triad of Map, Filter and FoldPhilip Schwarz
 
Building RESTful applications using Spring MVC
Building RESTful applications using Spring MVCBuilding RESTful applications using Spring MVC
Building RESTful applications using Spring MVCIndicThreads
 
Getting The Best Performance With PySpark
Getting The Best Performance With PySparkGetting The Best Performance With PySpark
Getting The Best Performance With PySparkSpark Summit
 
A simple introduction to redis
A simple introduction to redisA simple introduction to redis
A simple introduction to redisZhichao Liang
 
Golang 高性能实战
Golang 高性能实战Golang 高性能实战
Golang 高性能实战rfyiamcool
 
Linux and H/W optimizations for MySQL
Linux and H/W optimizations for MySQLLinux and H/W optimizations for MySQL
Linux and H/W optimizations for MySQLYoshinori Matsunobu
 

What's hot (20)

Ruby on Rails Presentation
Ruby on Rails PresentationRuby on Rails Presentation
Ruby on Rails Presentation
 
Collections - Maps
Collections - Maps Collections - Maps
Collections - Maps
 
Introduction to Python Celery
Introduction to Python CeleryIntroduction to Python Celery
Introduction to Python Celery
 
Second Level Cache in JPA Explained
Second Level Cache in JPA ExplainedSecond Level Cache in JPA Explained
Second Level Cache in JPA Explained
 
Nitro for your Grails App: how to improve performance. Greach '18
Nitro for your Grails App: how to improve performance. Greach '18Nitro for your Grails App: how to improve performance. Greach '18
Nitro for your Grails App: how to improve performance. Greach '18
 
The Java memory model made easy
The Java memory model made easyThe Java memory model made easy
The Java memory model made easy
 
PHP - Introduction to PHP AJAX
PHP -  Introduction to PHP AJAXPHP -  Introduction to PHP AJAX
PHP - Introduction to PHP AJAX
 
Monadic Java
Monadic JavaMonadic Java
Monadic Java
 
Introducing Async/Await
Introducing Async/AwaitIntroducing Async/Await
Introducing Async/Await
 
Dynamic Components using Single-Page-Application Concepts in AEM/CQ
Dynamic Components using Single-Page-Application Concepts in AEM/CQDynamic Components using Single-Page-Application Concepts in AEM/CQ
Dynamic Components using Single-Page-Application Concepts in AEM/CQ
 
Percona XtraDB Cluster ( Ensure high Availability )
Percona XtraDB Cluster ( Ensure high Availability )Percona XtraDB Cluster ( Ensure high Availability )
Percona XtraDB Cluster ( Ensure high Availability )
 
Java Server Faces (JSF) - Basics
Java Server Faces (JSF) - BasicsJava Server Faces (JSF) - Basics
Java Server Faces (JSF) - Basics
 
The Functional Programming Triad of Map, Filter and Fold
The Functional Programming Triad of Map, Filter and FoldThe Functional Programming Triad of Map, Filter and Fold
The Functional Programming Triad of Map, Filter and Fold
 
Building RESTful applications using Spring MVC
Building RESTful applications using Spring MVCBuilding RESTful applications using Spring MVC
Building RESTful applications using Spring MVC
 
Getting The Best Performance With PySpark
Getting The Best Performance With PySparkGetting The Best Performance With PySpark
Getting The Best Performance With PySpark
 
A simple introduction to redis
A simple introduction to redisA simple introduction to redis
A simple introduction to redis
 
Redis introduction
Redis introductionRedis introduction
Redis introduction
 
Grails audit logging
Grails audit loggingGrails audit logging
Grails audit logging
 
Golang 高性能实战
Golang 高性能实战Golang 高性能实战
Golang 高性能实战
 
Linux and H/W optimizations for MySQL
Linux and H/W optimizations for MySQLLinux and H/W optimizations for MySQL
Linux and H/W optimizations for MySQL
 

Similar to Understanding Database Transactions and Hibernate Sessions in Grails

Arquitetando seu app Android com Jetpack
Arquitetando seu app Android com JetpackArquitetando seu app Android com Jetpack
Arquitetando seu app Android com JetpackNelson Glauber Leal
 
Understanding GORM (Greach 2014)
Understanding GORM (Greach 2014)Understanding GORM (Greach 2014)
Understanding GORM (Greach 2014)Alonso Torres
 
Save your data
Save your dataSave your data
Save your datafragphace
 
LowlaDB intro March 2015
LowlaDB intro March 2015LowlaDB intro March 2015
LowlaDB intro March 2015Teamstudio
 
Hibernate Tutorial
Hibernate TutorialHibernate Tutorial
Hibernate TutorialRam132
 
Introduction tomongodb
Introduction tomongodbIntroduction tomongodb
Introduction tomongodbLee Theobald
 
Ceph Day Beijing - Our Journey to High Performance Large Scale Ceph Cluster a...
Ceph Day Beijing - Our Journey to High Performance Large Scale Ceph Cluster a...Ceph Day Beijing - Our Journey to High Performance Large Scale Ceph Cluster a...
Ceph Day Beijing - Our Journey to High Performance Large Scale Ceph Cluster a...Ceph Community
 
Ceph Day Beijing - Our journey to high performance large scale Ceph cluster a...
Ceph Day Beijing - Our journey to high performance large scale Ceph cluster a...Ceph Day Beijing - Our journey to high performance large scale Ceph cluster a...
Ceph Day Beijing - Our journey to high performance large scale Ceph cluster a...Danielle Womboldt
 
MongoDB .local Bengaluru 2019: Realm: The Secret Sauce for Better Mobile Apps
MongoDB .local Bengaluru 2019: Realm: The Secret Sauce for Better Mobile AppsMongoDB .local Bengaluru 2019: Realm: The Secret Sauce for Better Mobile Apps
MongoDB .local Bengaluru 2019: Realm: The Secret Sauce for Better Mobile AppsMongoDB
 
[db tech showcase Tokyo 2017] C23: Lessons from SQLite4 by SQLite.org - Richa...
[db tech showcase Tokyo 2017] C23: Lessons from SQLite4 by SQLite.org - Richa...[db tech showcase Tokyo 2017] C23: Lessons from SQLite4 by SQLite.org - Richa...
[db tech showcase Tokyo 2017] C23: Lessons from SQLite4 by SQLite.org - Richa...Insight Technology, Inc.
 
Bookie storage - Apache BookKeeper Meetup - 2015-06-28
Bookie storage - Apache BookKeeper Meetup - 2015-06-28 Bookie storage - Apache BookKeeper Meetup - 2015-06-28
Bookie storage - Apache BookKeeper Meetup - 2015-06-28 Matteo Merli
 
Hibernate jj
Hibernate jjHibernate jj
Hibernate jjJoe Jacob
 
REST APIs in Laravel 101
REST APIs in Laravel 101REST APIs in Laravel 101
REST APIs in Laravel 101Samantha Geitz
 
Getting Started with Rails
Getting Started with RailsGetting Started with Rails
Getting Started with RailsBasayel Said
 
Introduction to Apache Tajo: Data Warehouse for Big Data
Introduction to Apache Tajo: Data Warehouse for Big DataIntroduction to Apache Tajo: Data Warehouse for Big Data
Introduction to Apache Tajo: Data Warehouse for Big DataGruter
 
NoSQL: Why, When, and How
NoSQL: Why, When, and HowNoSQL: Why, When, and How
NoSQL: Why, When, and HowBigBlueHat
 
Apache Lucene intro - Breizhcamp 2015
Apache Lucene intro - Breizhcamp 2015Apache Lucene intro - Breizhcamp 2015
Apache Lucene intro - Breizhcamp 2015Adrien Grand
 
An introduction to Pincaster
An introduction to PincasterAn introduction to Pincaster
An introduction to PincasterFrank Denis
 
Intro to IndexedDB (Beta)
Intro to IndexedDB (Beta)Intro to IndexedDB (Beta)
Intro to IndexedDB (Beta)Mike West
 
Introduction to NHibernate
Introduction to NHibernateIntroduction to NHibernate
Introduction to NHibernateDublin Alt,Net
 

Similar to Understanding Database Transactions and Hibernate Sessions in Grails (20)

Arquitetando seu app Android com Jetpack
Arquitetando seu app Android com JetpackArquitetando seu app Android com Jetpack
Arquitetando seu app Android com Jetpack
 
Understanding GORM (Greach 2014)
Understanding GORM (Greach 2014)Understanding GORM (Greach 2014)
Understanding GORM (Greach 2014)
 
Save your data
Save your dataSave your data
Save your data
 
LowlaDB intro March 2015
LowlaDB intro March 2015LowlaDB intro March 2015
LowlaDB intro March 2015
 
Hibernate Tutorial
Hibernate TutorialHibernate Tutorial
Hibernate Tutorial
 
Introduction tomongodb
Introduction tomongodbIntroduction tomongodb
Introduction tomongodb
 
Ceph Day Beijing - Our Journey to High Performance Large Scale Ceph Cluster a...
Ceph Day Beijing - Our Journey to High Performance Large Scale Ceph Cluster a...Ceph Day Beijing - Our Journey to High Performance Large Scale Ceph Cluster a...
Ceph Day Beijing - Our Journey to High Performance Large Scale Ceph Cluster a...
 
Ceph Day Beijing - Our journey to high performance large scale Ceph cluster a...
Ceph Day Beijing - Our journey to high performance large scale Ceph cluster a...Ceph Day Beijing - Our journey to high performance large scale Ceph cluster a...
Ceph Day Beijing - Our journey to high performance large scale Ceph cluster a...
 
MongoDB .local Bengaluru 2019: Realm: The Secret Sauce for Better Mobile Apps
MongoDB .local Bengaluru 2019: Realm: The Secret Sauce for Better Mobile AppsMongoDB .local Bengaluru 2019: Realm: The Secret Sauce for Better Mobile Apps
MongoDB .local Bengaluru 2019: Realm: The Secret Sauce for Better Mobile Apps
 
[db tech showcase Tokyo 2017] C23: Lessons from SQLite4 by SQLite.org - Richa...
[db tech showcase Tokyo 2017] C23: Lessons from SQLite4 by SQLite.org - Richa...[db tech showcase Tokyo 2017] C23: Lessons from SQLite4 by SQLite.org - Richa...
[db tech showcase Tokyo 2017] C23: Lessons from SQLite4 by SQLite.org - Richa...
 
Bookie storage - Apache BookKeeper Meetup - 2015-06-28
Bookie storage - Apache BookKeeper Meetup - 2015-06-28 Bookie storage - Apache BookKeeper Meetup - 2015-06-28
Bookie storage - Apache BookKeeper Meetup - 2015-06-28
 
Hibernate jj
Hibernate jjHibernate jj
Hibernate jj
 
REST APIs in Laravel 101
REST APIs in Laravel 101REST APIs in Laravel 101
REST APIs in Laravel 101
 
Getting Started with Rails
Getting Started with RailsGetting Started with Rails
Getting Started with Rails
 
Introduction to Apache Tajo: Data Warehouse for Big Data
Introduction to Apache Tajo: Data Warehouse for Big DataIntroduction to Apache Tajo: Data Warehouse for Big Data
Introduction to Apache Tajo: Data Warehouse for Big Data
 
NoSQL: Why, When, and How
NoSQL: Why, When, and HowNoSQL: Why, When, and How
NoSQL: Why, When, and How
 
Apache Lucene intro - Breizhcamp 2015
Apache Lucene intro - Breizhcamp 2015Apache Lucene intro - Breizhcamp 2015
Apache Lucene intro - Breizhcamp 2015
 
An introduction to Pincaster
An introduction to PincasterAn introduction to Pincaster
An introduction to Pincaster
 
Intro to IndexedDB (Beta)
Intro to IndexedDB (Beta)Intro to IndexedDB (Beta)
Intro to IndexedDB (Beta)
 
Introduction to NHibernate
Introduction to NHibernateIntroduction to NHibernate
Introduction to NHibernate
 

Recently uploaded

How Does the Epitome of Spyware Differ from Other Malicious Software?
How Does the Epitome of Spyware Differ from Other Malicious Software?How Does the Epitome of Spyware Differ from Other Malicious Software?
How Does the Epitome of Spyware Differ from Other Malicious Software?AmeliaSmith90
 
Cybersecurity Challenges with Generative AI - for Good and Bad
Cybersecurity Challenges with Generative AI - for Good and BadCybersecurity Challenges with Generative AI - for Good and Bad
Cybersecurity Challenges with Generative AI - for Good and BadIvo Andreev
 
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...Jaydeep Chhasatia
 
Growing Oxen: channel operators and retries
Growing Oxen: channel operators and retriesGrowing Oxen: channel operators and retries
Growing Oxen: channel operators and retriesSoftwareMill
 
Why Choose Brain Inventory For Ecommerce Development.pdf
Why Choose Brain Inventory For Ecommerce Development.pdfWhy Choose Brain Inventory For Ecommerce Development.pdf
Why Choose Brain Inventory For Ecommerce Development.pdfBrain Inventory
 
Webinar_050417_LeClair12345666777889.ppt
Webinar_050417_LeClair12345666777889.pptWebinar_050417_LeClair12345666777889.ppt
Webinar_050417_LeClair12345666777889.pptkinjal48
 
Deep Learning for Images with PyTorch - Datacamp
Deep Learning for Images with PyTorch - DatacampDeep Learning for Images with PyTorch - Datacamp
Deep Learning for Images with PyTorch - DatacampVICTOR MAESTRE RAMIREZ
 
Leveraging DxSherpa's Generative AI Services to Unlock Human-Machine Harmony
Leveraging DxSherpa's Generative AI Services to Unlock Human-Machine HarmonyLeveraging DxSherpa's Generative AI Services to Unlock Human-Machine Harmony
Leveraging DxSherpa's Generative AI Services to Unlock Human-Machine Harmonyelliciumsolutionspun
 
Kawika Technologies pvt ltd Software Development Company in Trivandrum
Kawika Technologies pvt ltd Software Development Company in TrivandrumKawika Technologies pvt ltd Software Development Company in Trivandrum
Kawika Technologies pvt ltd Software Development Company in TrivandrumKawika Technologies
 
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...OnePlan Solutions
 
Top Software Development Trends in 2024
Top Software Development Trends in  2024Top Software Development Trends in  2024
Top Software Development Trends in 2024Mind IT Systems
 
IA Generativa y Grafos de Neo4j: RAG time
IA Generativa y Grafos de Neo4j: RAG timeIA Generativa y Grafos de Neo4j: RAG time
IA Generativa y Grafos de Neo4j: RAG timeNeo4j
 
Fields in Java and Kotlin and what to expect.pptx
Fields in Java and Kotlin and what to expect.pptxFields in Java and Kotlin and what to expect.pptx
Fields in Java and Kotlin and what to expect.pptxJoão Esperancinha
 
Sales Territory Management: A Definitive Guide to Expand Sales Coverage
Sales Territory Management: A Definitive Guide to Expand Sales CoverageSales Territory Management: A Definitive Guide to Expand Sales Coverage
Sales Territory Management: A Definitive Guide to Expand Sales CoverageDista
 
ERP For Electrical and Electronics manufecturing.pptx
ERP For Electrical and Electronics manufecturing.pptxERP For Electrical and Electronics manufecturing.pptx
ERP For Electrical and Electronics manufecturing.pptxAutus Cyber Tech
 
Introduction-to-Software-Development-Outsourcing.pptx
Introduction-to-Software-Development-Outsourcing.pptxIntroduction-to-Software-Development-Outsourcing.pptx
Introduction-to-Software-Development-Outsourcing.pptxIntelliSource Technologies
 
Streamlining Your Application Builds with Cloud Native Buildpacks
Streamlining Your Application Builds  with Cloud Native BuildpacksStreamlining Your Application Builds  with Cloud Native Buildpacks
Streamlining Your Application Builds with Cloud Native BuildpacksVish Abrams
 
AI Embracing Every Shade of Human Beauty
AI Embracing Every Shade of Human BeautyAI Embracing Every Shade of Human Beauty
AI Embracing Every Shade of Human BeautyRaymond Okyere-Forson
 
Watermarking in Source Code: Applications and Security Challenges
Watermarking in Source Code: Applications and Security ChallengesWatermarking in Source Code: Applications and Security Challenges
Watermarking in Source Code: Applications and Security ChallengesShyamsundar Das
 

Recently uploaded (20)

How Does the Epitome of Spyware Differ from Other Malicious Software?
How Does the Epitome of Spyware Differ from Other Malicious Software?How Does the Epitome of Spyware Differ from Other Malicious Software?
How Does the Epitome of Spyware Differ from Other Malicious Software?
 
Cybersecurity Challenges with Generative AI - for Good and Bad
Cybersecurity Challenges with Generative AI - for Good and BadCybersecurity Challenges with Generative AI - for Good and Bad
Cybersecurity Challenges with Generative AI - for Good and Bad
 
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...
 
Salesforce AI Associate Certification.pptx
Salesforce AI Associate Certification.pptxSalesforce AI Associate Certification.pptx
Salesforce AI Associate Certification.pptx
 
Growing Oxen: channel operators and retries
Growing Oxen: channel operators and retriesGrowing Oxen: channel operators and retries
Growing Oxen: channel operators and retries
 
Why Choose Brain Inventory For Ecommerce Development.pdf
Why Choose Brain Inventory For Ecommerce Development.pdfWhy Choose Brain Inventory For Ecommerce Development.pdf
Why Choose Brain Inventory For Ecommerce Development.pdf
 
Webinar_050417_LeClair12345666777889.ppt
Webinar_050417_LeClair12345666777889.pptWebinar_050417_LeClair12345666777889.ppt
Webinar_050417_LeClair12345666777889.ppt
 
Deep Learning for Images with PyTorch - Datacamp
Deep Learning for Images with PyTorch - DatacampDeep Learning for Images with PyTorch - Datacamp
Deep Learning for Images with PyTorch - Datacamp
 
Leveraging DxSherpa's Generative AI Services to Unlock Human-Machine Harmony
Leveraging DxSherpa's Generative AI Services to Unlock Human-Machine HarmonyLeveraging DxSherpa's Generative AI Services to Unlock Human-Machine Harmony
Leveraging DxSherpa's Generative AI Services to Unlock Human-Machine Harmony
 
Kawika Technologies pvt ltd Software Development Company in Trivandrum
Kawika Technologies pvt ltd Software Development Company in TrivandrumKawika Technologies pvt ltd Software Development Company in Trivandrum
Kawika Technologies pvt ltd Software Development Company in Trivandrum
 
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...
 
Top Software Development Trends in 2024
Top Software Development Trends in  2024Top Software Development Trends in  2024
Top Software Development Trends in 2024
 
IA Generativa y Grafos de Neo4j: RAG time
IA Generativa y Grafos de Neo4j: RAG timeIA Generativa y Grafos de Neo4j: RAG time
IA Generativa y Grafos de Neo4j: RAG time
 
Fields in Java and Kotlin and what to expect.pptx
Fields in Java and Kotlin and what to expect.pptxFields in Java and Kotlin and what to expect.pptx
Fields in Java and Kotlin and what to expect.pptx
 
Sales Territory Management: A Definitive Guide to Expand Sales Coverage
Sales Territory Management: A Definitive Guide to Expand Sales CoverageSales Territory Management: A Definitive Guide to Expand Sales Coverage
Sales Territory Management: A Definitive Guide to Expand Sales Coverage
 
ERP For Electrical and Electronics manufecturing.pptx
ERP For Electrical and Electronics manufecturing.pptxERP For Electrical and Electronics manufecturing.pptx
ERP For Electrical and Electronics manufecturing.pptx
 
Introduction-to-Software-Development-Outsourcing.pptx
Introduction-to-Software-Development-Outsourcing.pptxIntroduction-to-Software-Development-Outsourcing.pptx
Introduction-to-Software-Development-Outsourcing.pptx
 
Streamlining Your Application Builds with Cloud Native Buildpacks
Streamlining Your Application Builds  with Cloud Native BuildpacksStreamlining Your Application Builds  with Cloud Native Buildpacks
Streamlining Your Application Builds with Cloud Native Buildpacks
 
AI Embracing Every Shade of Human Beauty
AI Embracing Every Shade of Human BeautyAI Embracing Every Shade of Human Beauty
AI Embracing Every Shade of Human Beauty
 
Watermarking in Source Code: Applications and Security Challenges
Watermarking in Source Code: Applications and Security ChallengesWatermarking in Source Code: Applications and Security Challenges
Watermarking in Source Code: Applications and Security Challenges
 

Understanding Database Transactions and Hibernate Sessions in Grails

  • 1. 1 Understanding Database Transactions and Hibernate Sessions in Grails jonas.witt@valsight.com @jonaswitt Jonas Witt Berlin Groovy User Group 2017-05-11
  • 2. 3 GORM/Hibernate: Introduction • Hibernate is a very powerful Java Object/Relational Mapping (ORM) framework that accesses relational databases via JDBC • GORM is Grails’ default ORM and uses Hibernate as one of its backends (others: Mongo, Neo4J, REST) • Both combined make persistence of your application’s domain model very convenient – but understanding the details is essential when using the frameworks in production
  • 3. 4 Today’s Focus: Saving Domain Objects • This talk will focus on saving domain objects, i.e. the behavior of abstraction layers between your author.save() call and (eventually) persistence • To better understand reading domain objects, consider: – Using Hibernate caching: http://gorm.grails.org/6.0.x/hibernate/manual/#advancedGORMF eatures – “hasMany Considered Harmful” by Burt Beckwith: https://www.youtube.com/watch?v=-nofscHeEuU
  • 5. 6 Hibernate: transactional write-behind class AuthorController { def sessionFactory def updateName() { Author author = Author.get(params.id) author.name = 'Donald Knuth' author.save() sessionFactory.currentSession.flush() render author as JSON } }
  • 6. 7 Hibernate: transactional write-behind 1) By default, a controller uses a non-transactional database connection 2) Saving a GORM object does not not necessarily flush the changes to the database – updates are batched for better performance 3) session.flush() or save(flush: true) forces the Hibernate session to be flushed Grails Controller Hibernate Session SQL Database HTTP PUT (start session) getConnection() (1) Author.get(id) (check 1st level cache) SELECT * FROM author WHERE id = ? author.name = "Donald Knuth" author.save() (2) session.flush() (3) UPDATE author SET ... WHERE id = ? 200 OK
  • 7. 8 Hibernate FlushMode 1) In order to guarantee correctness of the returned author list, Hibernate will flush pending changes (flushMode = AUTO, default in GORM < 6.1) FlushModes: ALWAYS, AUTO, COMMIT, MANUAL Grails Controller Hibernate Session SQL Database HTTP PUT author.name = "Donald Knuth" author.save() Author.list() (1) UPDATE author SET ... WHERE id = ? SELECT * FROM author 200 OK
  • 8. 10 Hibernate session: summary • The Hibernate session batches updates to the underlying database for performance reasons • FlushMode = AUTO triggers implicit flushes when querying the database would lead to an outdated response otherwise • Use explicit flush()/clear() to reduce size of Hibernate session
  • 10. 12 Updating entities without transactions Problems: • Concurrent requests will see a state where only some of the 4 books exists • When the action fails in between, the DB will be left in an inconsistent state class AuthorController { def createDefaultBooks() { Author author = Author.get(params.id) List books = (1..4).collect { new Book(author: author, title: "The Art of Computer Programming, Vol. $it") } books*.save(flush: true) render books as JSON } }
  • 11. 13 Updating entities without transactions Grails Controller Hibernate Session SQL Database HTTP PUT book1.save(flush: true) INSERT INTO books VALUES (?, ?, ?) book2.save(flush: true) INSERT INTO books VALUES (?, ?, ?) render books as JSON 200 OK
  • 12. 14 import grails.transaction.Transactional class AuthorController { @Transactional def createDefaultBooks() { Author author = Author.get(params.id) List books = (1..4).collect { new Book(author: author, title: "The Art of Computer Programming, Vol. $it") } books*.save(flush: true) render books as JSON } } Updating entities with transactions* (*) Don’t do this at home! Transactional behavior: CHECK! !
  • 13. 15 Updating entities with transactions* (*) Don’t do this at home! Grails Controller Hibernate Session Transaction SQL Database HTTP PUT @Transactional START TRANSACTION book1.save(flush: true) INSERT INTO books VALUES (?, ?, ?) book2.save(flush: true) INSERT INTO books VALUES (?, ?, ?) (end of action) COMMIT 200 OK
  • 15. 17 [https://en.wikipedia.org/wiki/Race_condition] “Race conditions arise in software when an application depends on the sequence or timing of processes or threads for it to operate properly.” “When adding a sleep() statement makes your program fail, there is a race condition” [Some clever programmer, somewhere]
  • 17. 19 Grails Controller Hibernate Session Transaction SQL Database HTTP PUT @Transactional START TRANSACTION book1.save(flush: true) INSERT INTO books VALUES (?, ?, ?) book2.save(flush: true) INSERT INTO books VALUES (?, ?, ?) (end of action) COMMIT render books as JSON 200 OK Updating entities with transactions* (*) Don’t do this at home!
  • 18. 20 Updating entities with transactions* (*) Don’t do this at home! Grails Controller Hibernate Session Transaction SQL Database HTTP PUT @Transactional START TRANSACTION book1.save(flush: true) INSERT INTO books VALUES (?, ?, ?) book2.save(flush: true) INSERT INTO books VALUES (?, ?, ?) render books as JSON 200 OK (end of action) COMMIT
  • 19. 21 Updating entities with transactions* (*) Don’t do this at home! Grails Controller Hibernate Session Transaction SQL Database HTTP PUT @Transactional START TRANSACTION book1.save(flush: true) INSERT INTO books VALUES (?, ?, ?) book2.save(flush: true) INSERT INTO books VALUES (?, ?, ?) render books as JSON 200 OK HTTP GET SELECT * FROM books WHERE id = ? 404 Not Found (end of action) COMMIT
  • 20. 22 Transactional by default! ! ! ! class AuthorService { def createDefaultBooks(Author author) { List books = (1..4).collect { new Book(author: author, title: "The Art of Computer Programming, Vol. $it") } books*.save(flush: true) return books } } class AuthorController { def authorService def createDefaultBooks() { Author author = Author.get(params.id) def books = authorService.createDefaultBooks(author) render books as JSON } }
  • 21. 23 • The Grails service provides @Transactional behavior by default • The service method boundaries encapsulate the business logic, and separate it from the HTTP request handling Grails Controller Service Transaction SQL Database HTTP PUT SELECT * FROM author WHERE id = ? @Transactional START TRANSACTION INSERT INTO books VALUES (?, ?, ?) INSERT INTO books VALUES (?, ?, ?) (end of transactional method) COMMIT render books as JSON 200 OK Updating entities with transactions: best practice
  • 22. 24 SQL transaction isolation Isolation level Dirty reads Non-repeatable reads Phantom reads Read Uncommitted may occur may occur may occur Read Committed don't occur may occur may occur Repeatable Read don't occur don't occur may occur Serializable don't occur don't occur don't occur [https://en.wikipedia.org/wiki/Isolation_(database_systems)] The default in many JDBC drivers
  • 23. 25 SQL transactions summary • Use transactions to ensure atomic updates of related objects • Be mindful of transaction boundaries • Best practice: – Let Controllers handle the HTTP request only: parse HTTP parameters / request body, and render the HTTP response – Services (transactional by default) should be used to manipulate GORM objects (both light + heavy lifting)