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

Transactions and Concurrency Control Patterns
Transactions and Concurrency Control PatternsTransactions and Concurrency Control Patterns
Transactions and Concurrency Control PatternsJ On The Beach
 
The Basics of MongoDB
The Basics of MongoDBThe Basics of MongoDB
The Basics of MongoDBvaluebound
 
Designing and Implementing a Real-time Data Lake with Dynamically Changing Sc...
Designing and Implementing a Real-time Data Lake with Dynamically Changing Sc...Designing and Implementing a Real-time Data Lake with Dynamically Changing Sc...
Designing and Implementing a Real-time Data Lake with Dynamically Changing Sc...Databricks
 
Apache Spark - Basics of RDD | Big Data Hadoop Spark Tutorial | CloudxLab
Apache Spark - Basics of RDD | Big Data Hadoop Spark Tutorial | CloudxLabApache Spark - Basics of RDD | Big Data Hadoop Spark Tutorial | CloudxLab
Apache Spark - Basics of RDD | Big Data Hadoop Spark Tutorial | CloudxLabCloudxLab
 
Running Apache Spark on a High-Performance Cluster Using RDMA and NVMe Flash ...
Running Apache Spark on a High-Performance Cluster Using RDMA and NVMe Flash ...Running Apache Spark on a High-Performance Cluster Using RDMA and NVMe Flash ...
Running Apache Spark on a High-Performance Cluster Using RDMA and NVMe Flash ...Databricks
 
Basics of MongoDB
Basics of MongoDB Basics of MongoDB
Basics of MongoDB Habilelabs
 
Gentle Introduction to Scala
Gentle Introduction to ScalaGentle Introduction to Scala
Gentle Introduction to ScalaFangda Wang
 
[211] HBase 기반 검색 데이터 저장소 (공개용)
[211] HBase 기반 검색 데이터 저장소 (공개용)[211] HBase 기반 검색 데이터 저장소 (공개용)
[211] HBase 기반 검색 데이터 저장소 (공개용)NAVER D2
 
Streaming Data Lakes using Kafka Connect + Apache Hudi | Vinoth Chandar, Apac...
Streaming Data Lakes using Kafka Connect + Apache Hudi | Vinoth Chandar, Apac...Streaming Data Lakes using Kafka Connect + Apache Hudi | Vinoth Chandar, Apac...
Streaming Data Lakes using Kafka Connect + Apache Hudi | Vinoth Chandar, Apac...HostedbyConfluent
 
Introduction to Hadoop
Introduction to HadoopIntroduction to Hadoop
Introduction to HadoopApache Apex
 
Introduction to Redis
Introduction to RedisIntroduction to Redis
Introduction to RedisDvir Volk
 
A Rusty introduction to Apache Arrow and how it applies to a time series dat...
A Rusty introduction to Apache Arrow and how it applies to a  time series dat...A Rusty introduction to Apache Arrow and how it applies to a  time series dat...
A Rusty introduction to Apache Arrow and how it applies to a time series dat...Andrew Lamb
 
Kotlin scope functions
Kotlin scope functionsKotlin scope functions
Kotlin scope functionsWaheed Nazir
 
Apache Spark Data Source V2 with Wenchen Fan and Gengliang Wang
Apache Spark Data Source V2 with Wenchen Fan and Gengliang WangApache Spark Data Source V2 with Wenchen Fan and Gengliang Wang
Apache Spark Data Source V2 with Wenchen Fan and Gengliang WangDatabricks
 

What's hot (20)

Transactions and Concurrency Control Patterns
Transactions and Concurrency Control PatternsTransactions and Concurrency Control Patterns
Transactions and Concurrency Control Patterns
 
The Basics of MongoDB
The Basics of MongoDBThe Basics of MongoDB
The Basics of MongoDB
 
Java reflection
Java reflectionJava reflection
Java reflection
 
Designing and Implementing a Real-time Data Lake with Dynamically Changing Sc...
Designing and Implementing a Real-time Data Lake with Dynamically Changing Sc...Designing and Implementing a Real-time Data Lake with Dynamically Changing Sc...
Designing and Implementing a Real-time Data Lake with Dynamically Changing Sc...
 
Apache Spark - Basics of RDD | Big Data Hadoop Spark Tutorial | CloudxLab
Apache Spark - Basics of RDD | Big Data Hadoop Spark Tutorial | CloudxLabApache Spark - Basics of RDD | Big Data Hadoop Spark Tutorial | CloudxLab
Apache Spark - Basics of RDD | Big Data Hadoop Spark Tutorial | CloudxLab
 
Hibernate
HibernateHibernate
Hibernate
 
Running Apache Spark on a High-Performance Cluster Using RDMA and NVMe Flash ...
Running Apache Spark on a High-Performance Cluster Using RDMA and NVMe Flash ...Running Apache Spark on a High-Performance Cluster Using RDMA and NVMe Flash ...
Running Apache Spark on a High-Performance Cluster Using RDMA and NVMe Flash ...
 
Mongo DB Presentation
Mongo DB PresentationMongo DB Presentation
Mongo DB Presentation
 
Basics of MongoDB
Basics of MongoDB Basics of MongoDB
Basics of MongoDB
 
Gentle Introduction to Scala
Gentle Introduction to ScalaGentle Introduction to Scala
Gentle Introduction to Scala
 
[211] HBase 기반 검색 데이터 저장소 (공개용)
[211] HBase 기반 검색 데이터 저장소 (공개용)[211] HBase 기반 검색 데이터 저장소 (공개용)
[211] HBase 기반 검색 데이터 저장소 (공개용)
 
Streaming Data Lakes using Kafka Connect + Apache Hudi | Vinoth Chandar, Apac...
Streaming Data Lakes using Kafka Connect + Apache Hudi | Vinoth Chandar, Apac...Streaming Data Lakes using Kafka Connect + Apache Hudi | Vinoth Chandar, Apac...
Streaming Data Lakes using Kafka Connect + Apache Hudi | Vinoth Chandar, Apac...
 
Introduction to Hadoop
Introduction to HadoopIntroduction to Hadoop
Introduction to Hadoop
 
Introduction to Redis
Introduction to RedisIntroduction to Redis
Introduction to Redis
 
A Rusty introduction to Apache Arrow and how it applies to a time series dat...
A Rusty introduction to Apache Arrow and how it applies to a  time series dat...A Rusty introduction to Apache Arrow and how it applies to a  time series dat...
A Rusty introduction to Apache Arrow and how it applies to a time series dat...
 
Kotlin scope functions
Kotlin scope functionsKotlin scope functions
Kotlin scope functions
 
Apache Spark Data Source V2 with Wenchen Fan and Gengliang Wang
Apache Spark Data Source V2 with Wenchen Fan and Gengliang WangApache Spark Data Source V2 with Wenchen Fan and Gengliang Wang
Apache Spark Data Source V2 with Wenchen Fan and Gengliang Wang
 
Redis overview
Redis overviewRedis overview
Redis overview
 
Broadleaf Presents Thymeleaf
Broadleaf Presents ThymeleafBroadleaf Presents Thymeleaf
Broadleaf Presents Thymeleaf
 
Flink Streaming
Flink StreamingFlink Streaming
Flink Streaming
 

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

办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 

Recently uploaded (20)

办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 

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)