SlideShare uma empresa Scribd logo
1 de 24
Baixar para ler 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

Mais conteúdo relacionado

Mais procurados

Better than you think: Handling JSON data in ClickHouse
Better than you think: Handling JSON data in ClickHouseBetter than you think: Handling JSON data in ClickHouse
Better than you think: Handling JSON data in ClickHouseAltinity Ltd
 
Extreme Replication - Performance Tuning Oracle GoldenGate
Extreme Replication - Performance Tuning Oracle GoldenGateExtreme Replication - Performance Tuning Oracle GoldenGate
Extreme Replication - Performance Tuning Oracle GoldenGateBobby Curtis
 
PostgreSQL 15 and its Major Features -(Aakash M - Mydbops) - Mydbops Opensour...
PostgreSQL 15 and its Major Features -(Aakash M - Mydbops) - Mydbops Opensour...PostgreSQL 15 and its Major Features -(Aakash M - Mydbops) - Mydbops Opensour...
PostgreSQL 15 and its Major Features -(Aakash M - Mydbops) - Mydbops Opensour...Mydbops
 
Solving PostgreSQL wicked problems
Solving PostgreSQL wicked problemsSolving PostgreSQL wicked problems
Solving PostgreSQL wicked problemsAlexander Korotkov
 
cstore_fdw: Columnar Storage for PostgreSQL
cstore_fdw: Columnar Storage for PostgreSQLcstore_fdw: Columnar Storage for PostgreSQL
cstore_fdw: Columnar Storage for PostgreSQLCitus Data
 
Grails object relational mapping: GORM
Grails object relational mapping: GORMGrails object relational mapping: GORM
Grails object relational mapping: GORMSaurabh Dixit
 
[pgday.Seoul 2022] PostgreSQL구조 - 윤성재
[pgday.Seoul 2022] PostgreSQL구조 - 윤성재[pgday.Seoul 2022] PostgreSQL구조 - 윤성재
[pgday.Seoul 2022] PostgreSQL구조 - 윤성재PgDay.Seoul
 
Your first ClickHouse data warehouse
Your first ClickHouse data warehouseYour first ClickHouse data warehouse
Your first ClickHouse data warehouseAltinity Ltd
 
Analytic & Windowing functions in oracle
Analytic & Windowing functions in oracleAnalytic & Windowing functions in oracle
Analytic & Windowing functions in oracleLogan Palanisamy
 
ClickHouse and the Magic of Materialized Views, By Robert Hodges and Altinity...
ClickHouse and the Magic of Materialized Views, By Robert Hodges and Altinity...ClickHouse and the Magic of Materialized Views, By Robert Hodges and Altinity...
ClickHouse and the Magic of Materialized Views, By Robert Hodges and Altinity...Altinity Ltd
 
Real-time Analytics with Presto and Apache Pinot
Real-time Analytics with Presto and Apache PinotReal-time Analytics with Presto and Apache Pinot
Real-time Analytics with Presto and Apache PinotXiang Fu
 
Streaming Event Time Partitioning with Apache Flink and Apache Iceberg - Juli...
Streaming Event Time Partitioning with Apache Flink and Apache Iceberg - Juli...Streaming Event Time Partitioning with Apache Flink and Apache Iceberg - Juli...
Streaming Event Time Partitioning with Apache Flink and Apache Iceberg - Juli...Flink Forward
 
Working with JSON Data in PostgreSQL vs. MongoDB
Working with JSON Data in PostgreSQL vs. MongoDBWorking with JSON Data in PostgreSQL vs. MongoDB
Working with JSON Data in PostgreSQL vs. MongoDBScaleGrid.io
 
Reactive Web 101: WebFlux, WebClient, and Reactor Netty
Reactive Web 101: WebFlux, WebClient, and Reactor NettyReactive Web 101: WebFlux, WebClient, and Reactor Netty
Reactive Web 101: WebFlux, WebClient, and Reactor NettyVMware Tanzu
 
Introducing Drools
Introducing DroolsIntroducing Drools
Introducing DroolsMario Fusco
 
Slim Baltagi – Flink vs. Spark
Slim Baltagi – Flink vs. SparkSlim Baltagi – Flink vs. Spark
Slim Baltagi – Flink vs. SparkFlink Forward
 
All About JSON and ClickHouse - Tips, Tricks and New Features-2022-07-26-FINA...
All About JSON and ClickHouse - Tips, Tricks and New Features-2022-07-26-FINA...All About JSON and ClickHouse - Tips, Tricks and New Features-2022-07-26-FINA...
All About JSON and ClickHouse - Tips, Tricks and New Features-2022-07-26-FINA...Altinity Ltd
 

Mais procurados (20)

Better than you think: Handling JSON data in ClickHouse
Better than you think: Handling JSON data in ClickHouseBetter than you think: Handling JSON data in ClickHouse
Better than you think: Handling JSON data in ClickHouse
 
Extreme Replication - Performance Tuning Oracle GoldenGate
Extreme Replication - Performance Tuning Oracle GoldenGateExtreme Replication - Performance Tuning Oracle GoldenGate
Extreme Replication - Performance Tuning Oracle GoldenGate
 
PostgreSQL 15 and its Major Features -(Aakash M - Mydbops) - Mydbops Opensour...
PostgreSQL 15 and its Major Features -(Aakash M - Mydbops) - Mydbops Opensour...PostgreSQL 15 and its Major Features -(Aakash M - Mydbops) - Mydbops Opensour...
PostgreSQL 15 and its Major Features -(Aakash M - Mydbops) - Mydbops Opensour...
 
Solving PostgreSQL wicked problems
Solving PostgreSQL wicked problemsSolving PostgreSQL wicked problems
Solving PostgreSQL wicked problems
 
cstore_fdw: Columnar Storage for PostgreSQL
cstore_fdw: Columnar Storage for PostgreSQLcstore_fdw: Columnar Storage for PostgreSQL
cstore_fdw: Columnar Storage for PostgreSQL
 
How to Use JSON in MySQL Wrong
How to Use JSON in MySQL WrongHow to Use JSON in MySQL Wrong
How to Use JSON in MySQL Wrong
 
Grails object relational mapping: GORM
Grails object relational mapping: GORMGrails object relational mapping: GORM
Grails object relational mapping: GORM
 
[pgday.Seoul 2022] PostgreSQL구조 - 윤성재
[pgday.Seoul 2022] PostgreSQL구조 - 윤성재[pgday.Seoul 2022] PostgreSQL구조 - 윤성재
[pgday.Seoul 2022] PostgreSQL구조 - 윤성재
 
Your first ClickHouse data warehouse
Your first ClickHouse data warehouseYour first ClickHouse data warehouse
Your first ClickHouse data warehouse
 
Analytic & Windowing functions in oracle
Analytic & Windowing functions in oracleAnalytic & Windowing functions in oracle
Analytic & Windowing functions in oracle
 
PostgreSQL Replication Tutorial
PostgreSQL Replication TutorialPostgreSQL Replication Tutorial
PostgreSQL Replication Tutorial
 
ClickHouse and the Magic of Materialized Views, By Robert Hodges and Altinity...
ClickHouse and the Magic of Materialized Views, By Robert Hodges and Altinity...ClickHouse and the Magic of Materialized Views, By Robert Hodges and Altinity...
ClickHouse and the Magic of Materialized Views, By Robert Hodges and Altinity...
 
Real-time Analytics with Presto and Apache Pinot
Real-time Analytics with Presto and Apache PinotReal-time Analytics with Presto and Apache Pinot
Real-time Analytics with Presto and Apache Pinot
 
Streaming Event Time Partitioning with Apache Flink and Apache Iceberg - Juli...
Streaming Event Time Partitioning with Apache Flink and Apache Iceberg - Juli...Streaming Event Time Partitioning with Apache Flink and Apache Iceberg - Juli...
Streaming Event Time Partitioning with Apache Flink and Apache Iceberg - Juli...
 
Oracle ASM Training
Oracle ASM TrainingOracle ASM Training
Oracle ASM Training
 
Working with JSON Data in PostgreSQL vs. MongoDB
Working with JSON Data in PostgreSQL vs. MongoDBWorking with JSON Data in PostgreSQL vs. MongoDB
Working with JSON Data in PostgreSQL vs. MongoDB
 
Reactive Web 101: WebFlux, WebClient, and Reactor Netty
Reactive Web 101: WebFlux, WebClient, and Reactor NettyReactive Web 101: WebFlux, WebClient, and Reactor Netty
Reactive Web 101: WebFlux, WebClient, and Reactor Netty
 
Introducing Drools
Introducing DroolsIntroducing Drools
Introducing Drools
 
Slim Baltagi – Flink vs. Spark
Slim Baltagi – Flink vs. SparkSlim Baltagi – Flink vs. Spark
Slim Baltagi – Flink vs. Spark
 
All About JSON and ClickHouse - Tips, Tricks and New Features-2022-07-26-FINA...
All About JSON and ClickHouse - Tips, Tricks and New Features-2022-07-26-FINA...All About JSON and ClickHouse - Tips, Tricks and New Features-2022-07-26-FINA...
All About JSON and ClickHouse - Tips, Tricks and New Features-2022-07-26-FINA...
 

Semelhante a 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...Danielle Womboldt
 
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
 
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
 

Semelhante a 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
 

Último

Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 

Último (20)

Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 

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)