SlideShare a Scribd company logo
DB Locking
by Marek Hudyma
Agenda
● Optimistic read
● Pessimistic read
● Pessimistic write
● Real problem (concurrent calls)
Disclaimer
I will talk only about:
● Hibernate + Spring
● Postgres DB
● Isolation level = read commited
● You can lock resources in many ways.
● There are other locking methods in SQL
@Lock - how to use in JpaRepository
@Repository
public interface EntityRepository extends JpaRepository<Entity, Long> {
@Lock(LockModeType.PESSIMISTIC_WRITE)
Entity findOne(Long id);
}
@Repository
public interface EntityRepository extends JpaRepository<Entity, Long> {
@Lock(LockModeType.PESSIMISTIC_WRITE) // IT WILL NOT WORK
default Card findOneAndLock(String id) {
return findOne(id);
}
}
LockModeType.NONE
LockModeType.NONE
● select entity_.created as created2_2_ from entity entity_
where entity_.id=?
update entity_without_version set created=?,
description=? where id=?
● The row would have value set by transaction 2.
LockModeType.OPTIMISTIC (synonym READ)
● Add @Version field in your entity. Supported types:
int, Integer, short, Short, long, Long, java.sql.Timestamp
● If there is a different version of @Version field in the database,
ObjectOptimisticLockingFailureException is thrown.
● select entitywith0_.id ... from entity entity0_ where entity0_.id=?
● update entity set created=?, description=?, version=? where id=? and
version=?
● The version has been updated:
○ at the end of transaction
○ every time we call saveAndFlush
LockModeType.OPTIMISTIC (synonym READ)
LockModeType.OPTIMISTIC_FORCE_INCREMENT
(synonym WRITE)
● OPTIMISTIC_FORCE_INCREMENT works in the same way as OPTIMISTIC
but it increment version value every time.
LockModeType.PESSIMISTIC_READ
● Hibernate: select entity0_.id as id1_2_0_, entity0_.created as created2_2_0_,
entity0_.description as descript3_2_0_ from entity entity0_ where
entity0_.id=? for share
● Other transactions may concurrently read the entity, but cannot concurrently
update it (if both use “select for share”).
● There is a deadlock if two transactions use PESSIMISTIC_READ and try to
modify the row.
Random transaction interrupted with this exception (no matter which one
started first).
● You can still read data using classical repository (without any locking
strategy).
LockModeType.PESSIMISTIC_READ
LockModeType.PESSIMISTIC_WRITE
● Other transactions cannot concurrently read or write the entity (if both use
“select for update”).
● You can still read data using classical repository (without any locking
strategy).
● select entity0_.id as id1_2_0_, entity0_.created as created2_2_0_,
entity0_.description as descript3_2_0_ from entity entity0_ where
entity0_.id=? for update
LockModeType.PESSIMISTIC_WRITE
MIX - PESSIMISTIC_WRITE + OPTIMISTIC
● You can mix PESSIMISTIC_WRITE + OPTIMISTIC
● Add version field and use PESSIMISTIC_WRITE
Concurrent calls case
We wanted:
● Insert account and operations associated with it.
● If account exist, just insert operations.
● We don’t want to fail if two parallel requests come and
there is no account.
Concurrent calls case
INSERT ON CONFLICT DO NOTHING
INSERT INTO Accounts (id, … ) VALUES(...)
ON CONFLICT (id) DO NOTHING
Query will not fail if account.id existed before.
Concurrent calls solution
BEGIN TRANSACTION
SELECT * FROM ACCOUNTS FOR UPDATE WHERE ID = {id}
IF(result_of_select == null) {
INSERT INTO ACCOUNTS (id, ..) VALUES (...) ON
CONFLICT DO NOTHING
COMMIT
BEGIN TRANSACTION
SELECT * FROM ACCOUNTS FOR UPDATE WHERE ID = {id}
}
INSERT OPERATIONS
COMMIT
There was an account in DB
BEGIN TRANSACTION
SELECT * FROM ACCOUNTS FOR UPDATE WHERE ID = {id}
INSERT OPERATIONS
COMMIT
There was no account in DB
BEGIN TRANSACTION
SELECT * FROM ACCOUNTS FOR UPDATE WHERE ID = {id}
INSERT INTO ACCOUNTS (id, ..) VALUES (...) ON CONFLICT DO NOTHING
COMMIT
BEGIN TRANSACTION
SELECT * FROM ACCOUNTS FOR UPDATE WHERE ID = {id}
INSERT OPERATIONS
COMMIT
Alternative solutions
● Serializable isolation level
● Read committed isolation level + locking table
Serializable isolation level
● Puts transactions in order
● If not possible SQLException is thrown and
transaction need to be repeated.
● Serializable isolation level has other
disadvantages.
Read committed isolation level + locking table
● Table account_lock was created
● At the beginning of transaction insert was made
● Other transaction was blocked
● At the end of transaction row was deleted
● Vacuuming used a lot of resources
Comparison - locking table vs locking
https://github.com/marekhudyma/db-locking
Alternative locking
● Redis
● File system
Thank you !
Questions ?

More Related Content

What's hot

What's hot (20)

java API for XML DOM
java API for XML DOMjava API for XML DOM
java API for XML DOM
 
Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By Step
 
Devoxx08 - Nuxeo Core, JCR 2, CMIS
Devoxx08 - Nuxeo Core, JCR 2, CMIS Devoxx08 - Nuxeo Core, JCR 2, CMIS
Devoxx08 - Nuxeo Core, JCR 2, CMIS
 
Jpa 2.1 Application Development
Jpa 2.1 Application DevelopmentJpa 2.1 Application Development
Jpa 2.1 Application Development
 
Intro To Hibernate
Intro To HibernateIntro To Hibernate
Intro To Hibernate
 
Hibernate
HibernateHibernate
Hibernate
 
jpa-hibernate-presentation
jpa-hibernate-presentationjpa-hibernate-presentation
jpa-hibernate-presentation
 
hibernate with JPA
hibernate with JPAhibernate with JPA
hibernate with JPA
 
04 Data Access
04 Data Access04 Data Access
04 Data Access
 
JPA For Beginner's
JPA For Beginner'sJPA For Beginner's
JPA For Beginner's
 
A glimpse into protocols with associated type and type erasure
A glimpse into protocols with associated type and type erasureA glimpse into protocols with associated type and type erasure
A glimpse into protocols with associated type and type erasure
 
Hibernate An Introduction
Hibernate An IntroductionHibernate An Introduction
Hibernate An Introduction
 
Hibernate Session 1
Hibernate Session 1Hibernate Session 1
Hibernate Session 1
 
Ecom lec4 fall16_jpa
Ecom lec4 fall16_jpaEcom lec4 fall16_jpa
Ecom lec4 fall16_jpa
 
Introduction to JPA Framework
Introduction to JPA FrameworkIntroduction to JPA Framework
Introduction to JPA Framework
 
JPA Best Practices
JPA Best PracticesJPA Best Practices
JPA Best Practices
 
Lecture 2, c++(complete reference,herbet sheidt)chapter-12
Lecture 2, c++(complete reference,herbet sheidt)chapter-12Lecture 2, c++(complete reference,herbet sheidt)chapter-12
Lecture 2, c++(complete reference,herbet sheidt)chapter-12
 
Deployment
DeploymentDeployment
Deployment
 
Op ps
Op psOp ps
Op ps
 
JPA 2.0
JPA 2.0JPA 2.0
JPA 2.0
 

Similar to Db locking

Accessing data through hibernate: what DBAs should tell to developers and vic...
Accessing data through hibernate: what DBAs should tell to developers and vic...Accessing data through hibernate: what DBAs should tell to developers and vic...
Accessing data through hibernate: what DBAs should tell to developers and vic...Marco Tusa
 
Accessing Data Through Hibernate; What DBAs Should Tell Developers and Vice V...
Accessing Data Through Hibernate; What DBAs Should Tell Developers and Vice V...Accessing Data Through Hibernate; What DBAs Should Tell Developers and Vice V...
Accessing Data Through Hibernate; What DBAs Should Tell Developers and Vice V...Marco Tusa
 
MySQL Transaction Isolation Levels (lightning talk)
MySQL Transaction Isolation Levels (lightning talk)MySQL Transaction Isolation Levels (lightning talk)
MySQL Transaction Isolation Levels (lightning talk)Federico Razzoli
 
Get expertise with mongo db
Get expertise with mongo dbGet expertise with mongo db
Get expertise with mongo dbAmit Thakkar
 
Scala Frameworks for Web Application 2016
Scala Frameworks for Web Application 2016Scala Frameworks for Web Application 2016
Scala Frameworks for Web Application 2016takezoe
 
Zend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching loggingZend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching loggingTricode (part of Dept)
 
The program will read the file like this, java homework6Bank sma.pdf
The program will read the file like this, java homework6Bank sma.pdfThe program will read the file like this, java homework6Bank sma.pdf
The program will read the file like this, java homework6Bank sma.pdfivylinvaydak64229
 
Intro to IndexedDB (Beta)
Intro to IndexedDB (Beta)Intro to IndexedDB (Beta)
Intro to IndexedDB (Beta)Mike West
 
How MySQL can boost (or kill) your application v2
How MySQL can boost (or kill) your application v2How MySQL can boost (or kill) your application v2
How MySQL can boost (or kill) your application v2Federico Razzoli
 
InnoDB: архитектура транзакционного хранилища (Константин Осипов)
InnoDB: архитектура транзакционного хранилища (Константин Осипов)InnoDB: архитектура транзакционного хранилища (Константин Осипов)
InnoDB: архитектура транзакционного хранилища (Константин Осипов)Ontico
 
Core2 Document - Java SCORE Overview.pptx.pdf
Core2 Document - Java SCORE Overview.pptx.pdfCore2 Document - Java SCORE Overview.pptx.pdf
Core2 Document - Java SCORE Overview.pptx.pdfThchTrngGia
 
clean code book summary - uncle bob - English version
clean code book summary - uncle bob - English versionclean code book summary - uncle bob - English version
clean code book summary - uncle bob - English versionsaber tabatabaee
 
Database madness with_mongoengine_and_sql_alchemy
Database madness with_mongoengine_and_sql_alchemyDatabase madness with_mongoengine_and_sql_alchemy
Database madness with_mongoengine_and_sql_alchemyJaime Buelta
 
0wn-premises: Bypassing Microsoft Defender for Identity
0wn-premises: Bypassing Microsoft Defender for Identity0wn-premises: Bypassing Microsoft Defender for Identity
0wn-premises: Bypassing Microsoft Defender for IdentityNikhil Mittal
 
Introduction to Active Record - Silicon Valley Ruby Conference 2007
Introduction to Active Record - Silicon Valley Ruby Conference 2007Introduction to Active Record - Silicon Valley Ruby Conference 2007
Introduction to Active Record - Silicon Valley Ruby Conference 2007Rabble .
 
Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007Rabble .
 

Similar to Db locking (20)

Accessing data through hibernate: what DBAs should tell to developers and vic...
Accessing data through hibernate: what DBAs should tell to developers and vic...Accessing data through hibernate: what DBAs should tell to developers and vic...
Accessing data through hibernate: what DBAs should tell to developers and vic...
 
Accessing Data Through Hibernate; What DBAs Should Tell Developers and Vice V...
Accessing Data Through Hibernate; What DBAs Should Tell Developers and Vice V...Accessing Data Through Hibernate; What DBAs Should Tell Developers and Vice V...
Accessing Data Through Hibernate; What DBAs Should Tell Developers and Vice V...
 
MySQL Transaction Isolation Levels (lightning talk)
MySQL Transaction Isolation Levels (lightning talk)MySQL Transaction Isolation Levels (lightning talk)
MySQL Transaction Isolation Levels (lightning talk)
 
Get expertise with mongo db
Get expertise with mongo dbGet expertise with mongo db
Get expertise with mongo db
 
Scala Frameworks for Web Application 2016
Scala Frameworks for Web Application 2016Scala Frameworks for Web Application 2016
Scala Frameworks for Web Application 2016
 
Zend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching loggingZend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching logging
 
Using Dojo
Using DojoUsing Dojo
Using Dojo
 
The program will read the file like this, java homework6Bank sma.pdf
The program will read the file like this, java homework6Bank sma.pdfThe program will read the file like this, java homework6Bank sma.pdf
The program will read the file like this, java homework6Bank sma.pdf
 
Intro to IndexedDB (Beta)
Intro to IndexedDB (Beta)Intro to IndexedDB (Beta)
Intro to IndexedDB (Beta)
 
How MySQL can boost (or kill) your application v2
How MySQL can boost (or kill) your application v2How MySQL can boost (or kill) your application v2
How MySQL can boost (or kill) your application v2
 
InnoDB: архитектура транзакционного хранилища (Константин Осипов)
InnoDB: архитектура транзакционного хранилища (Константин Осипов)InnoDB: архитектура транзакционного хранилища (Константин Осипов)
InnoDB: архитектура транзакционного хранилища (Константин Осипов)
 
Core2 Document - Java SCORE Overview.pptx.pdf
Core2 Document - Java SCORE Overview.pptx.pdfCore2 Document - Java SCORE Overview.pptx.pdf
Core2 Document - Java SCORE Overview.pptx.pdf
 
clean code book summary - uncle bob - English version
clean code book summary - uncle bob - English versionclean code book summary - uncle bob - English version
clean code book summary - uncle bob - English version
 
Transaction
TransactionTransaction
Transaction
 
Database madness with_mongoengine_and_sql_alchemy
Database madness with_mongoengine_and_sql_alchemyDatabase madness with_mongoengine_and_sql_alchemy
Database madness with_mongoengine_and_sql_alchemy
 
0wn-premises: Bypassing Microsoft Defender for Identity
0wn-premises: Bypassing Microsoft Defender for Identity0wn-premises: Bypassing Microsoft Defender for Identity
0wn-premises: Bypassing Microsoft Defender for Identity
 
Spring 3 to 4
Spring 3 to 4Spring 3 to 4
Spring 3 to 4
 
Introduction to Active Record - Silicon Valley Ruby Conference 2007
Introduction to Active Record - Silicon Valley Ruby Conference 2007Introduction to Active Record - Silicon Valley Ruby Conference 2007
Introduction to Active Record - Silicon Valley Ruby Conference 2007
 
Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007
 
Assignment.1
Assignment.1Assignment.1
Assignment.1
 

Recently uploaded

Online resume builder management system project report.pdf
Online resume builder management system project report.pdfOnline resume builder management system project report.pdf
Online resume builder management system project report.pdfKamal Acharya
 
Introduction to Machine Learning Unit-4 Notes for II-II Mechanical Engineering
Introduction to Machine Learning Unit-4 Notes for II-II Mechanical EngineeringIntroduction to Machine Learning Unit-4 Notes for II-II Mechanical Engineering
Introduction to Machine Learning Unit-4 Notes for II-II Mechanical EngineeringC Sai Kiran
 
Scaling in conventional MOSFET for constant electric field and constant voltage
Scaling in conventional MOSFET for constant electric field and constant voltageScaling in conventional MOSFET for constant electric field and constant voltage
Scaling in conventional MOSFET for constant electric field and constant voltageRCC Institute of Information Technology
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdfAhmedHussein950959
 
shape functions of 1D and 2 D rectangular elements.pptx
shape functions of 1D and 2 D rectangular elements.pptxshape functions of 1D and 2 D rectangular elements.pptx
shape functions of 1D and 2 D rectangular elements.pptxVishalDeshpande27
 
Laundry management system project report.pdf
Laundry management system project report.pdfLaundry management system project report.pdf
Laundry management system project report.pdfKamal Acharya
 
Hall booking system project report .pdf
Hall booking system project report  .pdfHall booking system project report  .pdf
Hall booking system project report .pdfKamal Acharya
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Electivekarthi keyan
 
LIGA(E)11111111111111111111111111111111111111111.ppt
LIGA(E)11111111111111111111111111111111111111111.pptLIGA(E)11111111111111111111111111111111111111111.ppt
LIGA(E)11111111111111111111111111111111111111111.pptssuser9bd3ba
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationRobbie Edward Sayers
 
Online blood donation management system project.pdf
Online blood donation management system project.pdfOnline blood donation management system project.pdf
Online blood donation management system project.pdfKamal Acharya
 
Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.PrashantGoswami42
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Dr.Costas Sachpazis
 
Courier management system project report.pdf
Courier management system project report.pdfCourier management system project report.pdf
Courier management system project report.pdfKamal Acharya
 
Danfoss NeoCharge Technology -A Revolution in 2024.pdf
Danfoss NeoCharge Technology -A Revolution in 2024.pdfDanfoss NeoCharge Technology -A Revolution in 2024.pdf
Danfoss NeoCharge Technology -A Revolution in 2024.pdfNurvisNavarroSanchez
 
Democratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek AryaDemocratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek Aryaabh.arya
 
fluid mechanics gate notes . gate all pyqs answer
fluid mechanics gate notes . gate all pyqs answerfluid mechanics gate notes . gate all pyqs answer
fluid mechanics gate notes . gate all pyqs answerapareshmondalnita
 
A CASE STUDY ON ONLINE TICKET BOOKING SYSTEM PROJECT.pdf
A CASE STUDY ON ONLINE TICKET BOOKING SYSTEM PROJECT.pdfA CASE STUDY ON ONLINE TICKET BOOKING SYSTEM PROJECT.pdf
A CASE STUDY ON ONLINE TICKET BOOKING SYSTEM PROJECT.pdfKamal Acharya
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwoodseandesed
 

Recently uploaded (20)

Online resume builder management system project report.pdf
Online resume builder management system project report.pdfOnline resume builder management system project report.pdf
Online resume builder management system project report.pdf
 
Introduction to Machine Learning Unit-4 Notes for II-II Mechanical Engineering
Introduction to Machine Learning Unit-4 Notes for II-II Mechanical EngineeringIntroduction to Machine Learning Unit-4 Notes for II-II Mechanical Engineering
Introduction to Machine Learning Unit-4 Notes for II-II Mechanical Engineering
 
Scaling in conventional MOSFET for constant electric field and constant voltage
Scaling in conventional MOSFET for constant electric field and constant voltageScaling in conventional MOSFET for constant electric field and constant voltage
Scaling in conventional MOSFET for constant electric field and constant voltage
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
 
shape functions of 1D and 2 D rectangular elements.pptx
shape functions of 1D and 2 D rectangular elements.pptxshape functions of 1D and 2 D rectangular elements.pptx
shape functions of 1D and 2 D rectangular elements.pptx
 
Laundry management system project report.pdf
Laundry management system project report.pdfLaundry management system project report.pdf
Laundry management system project report.pdf
 
Hall booking system project report .pdf
Hall booking system project report  .pdfHall booking system project report  .pdf
Hall booking system project report .pdf
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
 
LIGA(E)11111111111111111111111111111111111111111.ppt
LIGA(E)11111111111111111111111111111111111111111.pptLIGA(E)11111111111111111111111111111111111111111.ppt
LIGA(E)11111111111111111111111111111111111111111.ppt
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
 
Online blood donation management system project.pdf
Online blood donation management system project.pdfOnline blood donation management system project.pdf
Online blood donation management system project.pdf
 
Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
 
Courier management system project report.pdf
Courier management system project report.pdfCourier management system project report.pdf
Courier management system project report.pdf
 
Danfoss NeoCharge Technology -A Revolution in 2024.pdf
Danfoss NeoCharge Technology -A Revolution in 2024.pdfDanfoss NeoCharge Technology -A Revolution in 2024.pdf
Danfoss NeoCharge Technology -A Revolution in 2024.pdf
 
Democratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek AryaDemocratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek Arya
 
fluid mechanics gate notes . gate all pyqs answer
fluid mechanics gate notes . gate all pyqs answerfluid mechanics gate notes . gate all pyqs answer
fluid mechanics gate notes . gate all pyqs answer
 
A CASE STUDY ON ONLINE TICKET BOOKING SYSTEM PROJECT.pdf
A CASE STUDY ON ONLINE TICKET BOOKING SYSTEM PROJECT.pdfA CASE STUDY ON ONLINE TICKET BOOKING SYSTEM PROJECT.pdf
A CASE STUDY ON ONLINE TICKET BOOKING SYSTEM PROJECT.pdf
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
 

Db locking

  • 2. Agenda ● Optimistic read ● Pessimistic read ● Pessimistic write ● Real problem (concurrent calls)
  • 3. Disclaimer I will talk only about: ● Hibernate + Spring ● Postgres DB ● Isolation level = read commited ● You can lock resources in many ways. ● There are other locking methods in SQL
  • 4. @Lock - how to use in JpaRepository @Repository public interface EntityRepository extends JpaRepository<Entity, Long> { @Lock(LockModeType.PESSIMISTIC_WRITE) Entity findOne(Long id); } @Repository public interface EntityRepository extends JpaRepository<Entity, Long> { @Lock(LockModeType.PESSIMISTIC_WRITE) // IT WILL NOT WORK default Card findOneAndLock(String id) { return findOne(id); } }
  • 6. LockModeType.NONE ● select entity_.created as created2_2_ from entity entity_ where entity_.id=? update entity_without_version set created=?, description=? where id=? ● The row would have value set by transaction 2.
  • 7. LockModeType.OPTIMISTIC (synonym READ) ● Add @Version field in your entity. Supported types: int, Integer, short, Short, long, Long, java.sql.Timestamp ● If there is a different version of @Version field in the database, ObjectOptimisticLockingFailureException is thrown. ● select entitywith0_.id ... from entity entity0_ where entity0_.id=? ● update entity set created=?, description=?, version=? where id=? and version=? ● The version has been updated: ○ at the end of transaction ○ every time we call saveAndFlush
  • 9. LockModeType.OPTIMISTIC_FORCE_INCREMENT (synonym WRITE) ● OPTIMISTIC_FORCE_INCREMENT works in the same way as OPTIMISTIC but it increment version value every time.
  • 10. LockModeType.PESSIMISTIC_READ ● Hibernate: select entity0_.id as id1_2_0_, entity0_.created as created2_2_0_, entity0_.description as descript3_2_0_ from entity entity0_ where entity0_.id=? for share ● Other transactions may concurrently read the entity, but cannot concurrently update it (if both use “select for share”). ● There is a deadlock if two transactions use PESSIMISTIC_READ and try to modify the row. Random transaction interrupted with this exception (no matter which one started first). ● You can still read data using classical repository (without any locking strategy).
  • 12. LockModeType.PESSIMISTIC_WRITE ● Other transactions cannot concurrently read or write the entity (if both use “select for update”). ● You can still read data using classical repository (without any locking strategy). ● select entity0_.id as id1_2_0_, entity0_.created as created2_2_0_, entity0_.description as descript3_2_0_ from entity entity0_ where entity0_.id=? for update
  • 14. MIX - PESSIMISTIC_WRITE + OPTIMISTIC ● You can mix PESSIMISTIC_WRITE + OPTIMISTIC ● Add version field and use PESSIMISTIC_WRITE
  • 15. Concurrent calls case We wanted: ● Insert account and operations associated with it. ● If account exist, just insert operations. ● We don’t want to fail if two parallel requests come and there is no account.
  • 17. INSERT ON CONFLICT DO NOTHING INSERT INTO Accounts (id, … ) VALUES(...) ON CONFLICT (id) DO NOTHING Query will not fail if account.id existed before.
  • 18. Concurrent calls solution BEGIN TRANSACTION SELECT * FROM ACCOUNTS FOR UPDATE WHERE ID = {id} IF(result_of_select == null) { INSERT INTO ACCOUNTS (id, ..) VALUES (...) ON CONFLICT DO NOTHING COMMIT BEGIN TRANSACTION SELECT * FROM ACCOUNTS FOR UPDATE WHERE ID = {id} } INSERT OPERATIONS COMMIT
  • 19. There was an account in DB BEGIN TRANSACTION SELECT * FROM ACCOUNTS FOR UPDATE WHERE ID = {id} INSERT OPERATIONS COMMIT
  • 20. There was no account in DB BEGIN TRANSACTION SELECT * FROM ACCOUNTS FOR UPDATE WHERE ID = {id} INSERT INTO ACCOUNTS (id, ..) VALUES (...) ON CONFLICT DO NOTHING COMMIT BEGIN TRANSACTION SELECT * FROM ACCOUNTS FOR UPDATE WHERE ID = {id} INSERT OPERATIONS COMMIT
  • 21. Alternative solutions ● Serializable isolation level ● Read committed isolation level + locking table
  • 22. Serializable isolation level ● Puts transactions in order ● If not possible SQLException is thrown and transaction need to be repeated. ● Serializable isolation level has other disadvantages.
  • 23. Read committed isolation level + locking table ● Table account_lock was created ● At the beginning of transaction insert was made ● Other transaction was blocked ● At the end of transaction row was deleted ● Vacuuming used a lot of resources
  • 24. Comparison - locking table vs locking