SlideShare a Scribd company logo
1 of 36
Grails
Services, Transactions & Async calls
Service
Service
Business logic goes in services.
Don’t use controllers to do any heavy lifting. They are designed only for controlling application flow and
doing data marshaling. All your data access and business logic should happen in transactional
services.
Also avoid much logic in Domain classes. Validation logic there can be limited to basic constraints and
basic postUpdate and postCreate methods.
Create Service
grails> create-service com.netflix.Contract
| Created file grails-app/services/com/netflix/ContractService.groovy
| Created file test/unit/com/netflix/ContractServiceTests.groovy
package com.netflix
class ContractService {
def serviceMethod() {
}
}
Session vs Transaction
User Session: Corresponds to time within which the user is logged in to the system.
Hibernate Session: Associated with JDBC Connection.
Hibernate Transaction: ACID compliant boundary for unit of work.
Scope
> singleton (default), prototype, request, session
class SomeUsefulService {
// this is a request scoped service
static scope = 'request'
}
Service Injection
class ContractController {
ContractService contractService
...
}
No need for AutoWire annotation.
Command Objects
@grails.validation.Validateable
class LoginCommand {
def loginService
String username
String password
static constraints = {
username validator: { val, obj ->
obj.loginService.canLogin(obj.username, obj.password)
}
}
}
Transaction
@Transactional annotation
Service methods are Transactional by default. However best practice is to add @Transactional
annotation to each service
Transaction annotation is similar to Spring’s @Transactional annotation
The @Transactional annotation on the class ensures that all public methods in a service are
transactional.
Annotating a service method (and not at class) with @Transactional disables the default Grails
transactional behavior for that method. so if you use any annotations you must annotate all methods
that require transactions.
Example
import grails.transaction.Transactional
@Transactional
class BookService {
@Transactional(readOnly = true)
def listBooks() {
Book.list()
}
def updateBook() {
// …
}
}
No Transaction & ReadOnly
@NonTransactional
class EmailService {
//OR static transactional = false
….
}
@Transactional(readOnly = true)
class ReportService {
….
}
withTransaction
package com.netflix
class ContractService {
// turn off automatic transaction management
static transactional = false
void someServiceMethod() {
Contract.withTransaction {TransactionStatus tx ->
// do some work with the database….
// if the transaction needs to be rolled back, call setRollbackOnly()
tx.setRollbackOnly()
}
}
}
Savepoint
def save() {
Album.withTransaction { status ->
def album = Album.get(params.id)
album.title = "Changed Title"
album.save(flush:true)
def savepoint = status.createSavepoint()
...
// something goes wrong
if(hasSomethingGoneWrong()) {
status.rollbackToSavepoint(savepoint)
// do something else
...
} } }
Transaction Propagation :(
// Doesn’t work well without additional configuration
@Transactional
void someMethod(...) {
// do some work ...
storeAuditData(...)
}
@Transactional(propagation=Propagation.REQUIRES_NEW)
void storeAuditData(...) {
//
}
http://techbus.safaribooksonline.com/book/programming/9781449324513/4dot-
spring/_transactional_services_html
Error Handling
Exceptions and Validations
class AuthorService {
void updateAge(id, int age) {
def author = Author.get(id)
author.age = age
if (author.isTooOld()) {
throw new AuthorException("too old", author)
}
if (!author.validate()) {
throw new ValidationException("Author is not valid", author.errors)
}
}
}
Exception on Save
def p = Person.get(1)
try {
p.save(failOnError: true)
}
catch (ValidationException e) {
// deal with exception
p.errors.allErrors.each {
println it
}
}
LazyInitializationException
When a transaction is rolled back the Hibernate session used by GORM is cleared. This means any
objects within the session become detached and accessing uninitialized lazy-loaded collections will
lead to LazyInitializationException
class AuthorController {
def authorService
def updateAge() {
try {
authorService.updateAge(params.id, params.int("age"))
} catch(e) {
render "Author books ${e.author.books}"
}
} }
Solution...
class AuthorService {
void updateAge(id, int age) {
def author = Author.findById(id, [fetch:[books:"eager"]])
author.age = age
if (author.isTooOld()) {
throw new AuthorException("too old", author)
}
}
}
Sample
Asynchronous
Various ways...
● Event mechanism using Platform Core
plugin
● JMS Messaging Queues Plugin
● Quartz scheduling Plugin
● Asynchronous Programming
Asynchronous - Promise
import static java.util.concurrent.TimeUnit.*
import static grails.async.Promises.*
Promise p = Promises.task {
// Long running task
}
p.onError { Throwable err ->
println "An error occured ${err.message}"
}
p.onComplete { result ->
println "Promise returned $result"
}
Synchronous - Promise
import static java.util.concurrent.TimeUnit.*
import static grails.async.Promises.*
Promise p = task {
// Long running task
}
…. other tasks
// block until result is called
def result = p.get()
// block for the specified time
def result = p.get(1,MINUTES)
PromiseList
import static grails.async.Promises.*
import grails.async.PromiseList
PromiseList promiseList = tasks([{ 2 * 2 }, { 4 * 4}, { 8 * 8 }])
//... some other processes
assert [4,16,64] == promiseList.get()
PromiseMap
import grails.async.*
PromiseMap map = new PromiseMap()
map['one'] = { 2 * 2 }
map['two'] = { 4 * 4 }
map['three'] = { 8 * 8 }
//Async call
map.onComplete { Map results ->
assert [one:4,two:16,three:64] == results
}
DelegateAsync Transformation
//Sync service
class BookService {
List<Book> findBooks(String title) {
// implementation
}
}
//Async Service
import grails.async.*
class AsyncBookService {
@DelegateAsync BookService bookService
}
DelegateAsync call
//Async service call
AsyncBookService asyncBookService
def findBooks(String title) {
asyncBookService.findBooks(title)
.onComplete { List results ->
println "Books = ${results}"
}
}
Asynchronous GORM
import static grails.async.Promises.*
Person.async.list().onComplete { List results ->
println "Got people = ${results}"
}
PromiseList p = Person.async.getAll(1L, 2L, 3L)
List results = p.get()
Promise p1 = Person.async.findByFirstName("Homer")
Promise p2 = Person.async.findByFirstName("Bart")
Promise p3 = Person.async.findByFirstName("Barney")
results = waitAll(p1, p2, p3)
Async and the Session
When using GORM async each promise is executed in a different thread. Since the Hibernate session
is not concurrency safe, a new session is bound per thread.
This means you cannot save objects returned from asynchronous queries without first merging them
back into session.
def promise = Person.async.findByFirstName("Homer")
def person = promise.get()
person.merge()
person.firstName = "Bart"
In general it is not recommended to read and write objects in different threads and you should avoid
this technique unless absolutely necessary. Also fetch the dependent objects eagerly to avoid
LazyInitializationException
Quartz
plugins {
...
compile ":quartz:1.0.1"
...
}
//New commands
grails create-job
grails install-quartz-config
grails create-job com.netflix.SupplierImport
spock
Testing Services

More Related Content

What's hot

Asynchronous JS in Odoo
Asynchronous JS in OdooAsynchronous JS in Odoo
Asynchronous JS in OdooOdoo
 
Java 8 - interfaces
Java 8 - interfacesJava 8 - interfaces
Java 8 - interfacesFranck SIMON
 
JUnit5 and TestContainers
JUnit5 and TestContainersJUnit5 and TestContainers
JUnit5 and TestContainersSunghyouk Bae
 
Building Grails applications with PostgreSQL
Building Grails applications with PostgreSQLBuilding Grails applications with PostgreSQL
Building Grails applications with PostgreSQLCommand Prompt., Inc
 
Asynchronous programming in C#
Asynchronous programming in C#Asynchronous programming in C#
Asynchronous programming in C#Bohdan Pashkovskyi
 
Sum and Product Types - The Fruit Salad & Fruit Snack Example - From F# to Ha...
Sum and Product Types -The Fruit Salad & Fruit Snack Example - From F# to Ha...Sum and Product Types -The Fruit Salad & Fruit Snack Example - From F# to Ha...
Sum and Product Types - The Fruit Salad & Fruit Snack Example - From F# to Ha...Philip Schwarz
 
Monad as functor with pair of natural transformations
Monad as functor with pair of natural transformationsMonad as functor with pair of natural transformations
Monad as functor with pair of natural transformationsPhilip Schwarz
 
Google Guava for cleaner code
Google Guava for cleaner codeGoogle Guava for cleaner code
Google Guava for cleaner codeMite Mitreski
 
An Introduction to Celery
An Introduction to CeleryAn Introduction to Celery
An Introduction to CeleryIdan Gazit
 
Asynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & PromisesAsynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & PromisesHùng Nguyễn Huy
 
Grails object relational mapping: GORM
Grails object relational mapping: GORMGrails object relational mapping: GORM
Grails object relational mapping: GORMSaurabh Dixit
 
Gitflow - Branching and Merging Flow for Git
Gitflow - Branching and Merging Flow for GitGitflow - Branching and Merging Flow for Git
Gitflow - Branching and Merging Flow for GitMaulik Shah
 

What's hot (20)

Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
Asynchronous JS in Odoo
Asynchronous JS in OdooAsynchronous JS in Odoo
Asynchronous JS in Odoo
 
Git & GitHub for Beginners
Git & GitHub for BeginnersGit & GitHub for Beginners
Git & GitHub for Beginners
 
Java 8 - interfaces
Java 8 - interfacesJava 8 - interfaces
Java 8 - interfaces
 
JUnit5 and TestContainers
JUnit5 and TestContainersJUnit5 and TestContainers
JUnit5 and TestContainers
 
Building Grails applications with PostgreSQL
Building Grails applications with PostgreSQLBuilding Grails applications with PostgreSQL
Building Grails applications with PostgreSQL
 
Asynchronous programming in C#
Asynchronous programming in C#Asynchronous programming in C#
Asynchronous programming in C#
 
Sum and Product Types - The Fruit Salad & Fruit Snack Example - From F# to Ha...
Sum and Product Types -The Fruit Salad & Fruit Snack Example - From F# to Ha...Sum and Product Types -The Fruit Salad & Fruit Snack Example - From F# to Ha...
Sum and Product Types - The Fruit Salad & Fruit Snack Example - From F# to Ha...
 
Meta Programming in Groovy
Meta Programming in GroovyMeta Programming in Groovy
Meta Programming in Groovy
 
Introduction to Git and GitHub
Introduction to Git and GitHubIntroduction to Git and GitHub
Introduction to Git and GitHub
 
Intro GraphQL
Intro GraphQLIntro GraphQL
Intro GraphQL
 
Monad as functor with pair of natural transformations
Monad as functor with pair of natural transformationsMonad as functor with pair of natural transformations
Monad as functor with pair of natural transformations
 
Google Guava for cleaner code
Google Guava for cleaner codeGoogle Guava for cleaner code
Google Guava for cleaner code
 
An Introduction to Celery
An Introduction to CeleryAn Introduction to Celery
An Introduction to Celery
 
Asynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & PromisesAsynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & Promises
 
Grails object relational mapping: GORM
Grails object relational mapping: GORMGrails object relational mapping: GORM
Grails object relational mapping: GORM
 
Git Rebase vs Merge
Git Rebase vs MergeGit Rebase vs Merge
Git Rebase vs Merge
 
Gitflow - Branching and Merging Flow for Git
Gitflow - Branching and Merging Flow for GitGitflow - Branching and Merging Flow for Git
Gitflow - Branching and Merging Flow for Git
 
Introduction to kotlin
Introduction to kotlinIntroduction to kotlin
Introduction to kotlin
 
Git and GitHub
Git and GitHubGit and GitHub
Git and GitHub
 

Similar to Grails transactions

Job Queue in Golang
Job Queue in GolangJob Queue in Golang
Job Queue in GolangBo-Yi Wu
 
GDG Devfest 2019 - Build go kit microservices at kubernetes with ease
GDG Devfest 2019 - Build go kit microservices at kubernetes with easeGDG Devfest 2019 - Build go kit microservices at kubernetes with ease
GDG Devfest 2019 - Build go kit microservices at kubernetes with easeKAI CHU CHUNG
 
Scheduling tasks the human way - Brad Wood - ITB2021
Scheduling tasks the human way -  Brad Wood - ITB2021Scheduling tasks the human way -  Brad Wood - ITB2021
Scheduling tasks the human way - Brad Wood - ITB2021Ortus Solutions, Corp
 
如何透過 Go-kit 快速搭建微服務架構應用程式實戰
如何透過 Go-kit 快速搭建微服務架構應用程式實戰如何透過 Go-kit 快速搭建微服務架構應用程式實戰
如何透過 Go-kit 快速搭建微服務架構應用程式實戰KAI CHU CHUNG
 
Async Server Rendering in React+Redux at NYTimes (redux-taxi)
Async Server Rendering in React+Redux at NYTimes (redux-taxi)Async Server Rendering in React+Redux at NYTimes (redux-taxi)
Async Server Rendering in React+Redux at NYTimes (redux-taxi)Jeremy Gayed
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSAdam L Barrett
 
Advanced iOS Build Mechanics, Sebastien Pouliot
Advanced iOS Build Mechanics, Sebastien PouliotAdvanced iOS Build Mechanics, Sebastien Pouliot
Advanced iOS Build Mechanics, Sebastien PouliotXamarin
 
用 Go 語言打造多台機器 Scale 架構
用 Go 語言打造多台機器 Scale 架構用 Go 語言打造多台機器 Scale 架構
用 Go 語言打造多台機器 Scale 架構Bo-Yi Wu
 
Finagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at PinterestFinagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at PinterestPavan Chitumalla
 
Writing Docker monitoring agent with Go
Writing Docker monitoring agent with GoWriting Docker monitoring agent with Go
Writing Docker monitoring agent with GoNaoki AINOYA
 
The Ring programming language version 1.5.4 book - Part 8 of 185
The Ring programming language version 1.5.4 book - Part 8 of 185The Ring programming language version 1.5.4 book - Part 8 of 185
The Ring programming language version 1.5.4 book - Part 8 of 185Mahmoud Samir Fayed
 
Architecting Alive Apps
Architecting Alive AppsArchitecting Alive Apps
Architecting Alive AppsJorge Ortiz
 
こわくないよ❤️ Playframeworkソースコードリーディング入門
こわくないよ❤️ Playframeworkソースコードリーディング入門こわくないよ❤️ Playframeworkソースコードリーディング入門
こわくないよ❤️ Playframeworkソースコードリーディング入門tanacasino
 
Workshop: Async and Parallel in C#
Workshop: Async and Parallel in C#Workshop: Async and Parallel in C#
Workshop: Async and Parallel in C#Rainer Stropek
 
OSGi ecosystems compared on Apache Karaf - Christian Schneider
OSGi ecosystems compared on Apache Karaf - Christian SchneiderOSGi ecosystems compared on Apache Karaf - Christian Schneider
OSGi ecosystems compared on Apache Karaf - Christian Schneidermfrancis
 
How to perform debounce in react
How to perform debounce in reactHow to perform debounce in react
How to perform debounce in reactBOSC Tech Labs
 

Similar to Grails transactions (20)

Job Queue in Golang
Job Queue in GolangJob Queue in Golang
Job Queue in Golang
 
GDG Devfest 2019 - Build go kit microservices at kubernetes with ease
GDG Devfest 2019 - Build go kit microservices at kubernetes with easeGDG Devfest 2019 - Build go kit microservices at kubernetes with ease
GDG Devfest 2019 - Build go kit microservices at kubernetes with ease
 
Server Side Swift: Vapor
Server Side Swift: VaporServer Side Swift: Vapor
Server Side Swift: Vapor
 
Scheduling tasks the human way - Brad Wood - ITB2021
Scheduling tasks the human way -  Brad Wood - ITB2021Scheduling tasks the human way -  Brad Wood - ITB2021
Scheduling tasks the human way - Brad Wood - ITB2021
 
如何透過 Go-kit 快速搭建微服務架構應用程式實戰
如何透過 Go-kit 快速搭建微服務架構應用程式實戰如何透過 Go-kit 快速搭建微服務架構應用程式實戰
如何透過 Go-kit 快速搭建微服務架構應用程式實戰
 
gRPC in Go
gRPC in GogRPC in Go
gRPC in Go
 
Async Server Rendering in React+Redux at NYTimes (redux-taxi)
Async Server Rendering in React+Redux at NYTimes (redux-taxi)Async Server Rendering in React+Redux at NYTimes (redux-taxi)
Async Server Rendering in React+Redux at NYTimes (redux-taxi)
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
 
Advanced iOS Build Mechanics, Sebastien Pouliot
Advanced iOS Build Mechanics, Sebastien PouliotAdvanced iOS Build Mechanics, Sebastien Pouliot
Advanced iOS Build Mechanics, Sebastien Pouliot
 
用 Go 語言打造多台機器 Scale 架構
用 Go 語言打造多台機器 Scale 架構用 Go 語言打造多台機器 Scale 架構
用 Go 語言打造多台機器 Scale 架構
 
Finagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at PinterestFinagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at Pinterest
 
Writing Docker monitoring agent with Go
Writing Docker monitoring agent with GoWriting Docker monitoring agent with Go
Writing Docker monitoring agent with Go
 
The Ring programming language version 1.5.4 book - Part 8 of 185
The Ring programming language version 1.5.4 book - Part 8 of 185The Ring programming language version 1.5.4 book - Part 8 of 185
The Ring programming language version 1.5.4 book - Part 8 of 185
 
Kitura Todolist tutorial
Kitura Todolist tutorialKitura Todolist tutorial
Kitura Todolist tutorial
 
h-ubu - CDI in JavaScript
h-ubu - CDI in JavaScripth-ubu - CDI in JavaScript
h-ubu - CDI in JavaScript
 
Architecting Alive Apps
Architecting Alive AppsArchitecting Alive Apps
Architecting Alive Apps
 
こわくないよ❤️ Playframeworkソースコードリーディング入門
こわくないよ❤️ Playframeworkソースコードリーディング入門こわくないよ❤️ Playframeworkソースコードリーディング入門
こわくないよ❤️ Playframeworkソースコードリーディング入門
 
Workshop: Async and Parallel in C#
Workshop: Async and Parallel in C#Workshop: Async and Parallel in C#
Workshop: Async and Parallel in C#
 
OSGi ecosystems compared on Apache Karaf - Christian Schneider
OSGi ecosystems compared on Apache Karaf - Christian SchneiderOSGi ecosystems compared on Apache Karaf - Christian Schneider
OSGi ecosystems compared on Apache Karaf - Christian Schneider
 
How to perform debounce in react
How to perform debounce in reactHow to perform debounce in react
How to perform debounce in react
 

Recently uploaded

EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noidabntitsolutionsrishis
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
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
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfIdiosysTechnologies1
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfLivetecs LLC
 

Recently uploaded (20)

EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
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
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
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
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdf
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdf
 

Grails transactions

  • 3. Service Business logic goes in services. Don’t use controllers to do any heavy lifting. They are designed only for controlling application flow and doing data marshaling. All your data access and business logic should happen in transactional services. Also avoid much logic in Domain classes. Validation logic there can be limited to basic constraints and basic postUpdate and postCreate methods.
  • 4. Create Service grails> create-service com.netflix.Contract | Created file grails-app/services/com/netflix/ContractService.groovy | Created file test/unit/com/netflix/ContractServiceTests.groovy package com.netflix class ContractService { def serviceMethod() { } }
  • 5. Session vs Transaction User Session: Corresponds to time within which the user is logged in to the system. Hibernate Session: Associated with JDBC Connection. Hibernate Transaction: ACID compliant boundary for unit of work.
  • 6. Scope > singleton (default), prototype, request, session class SomeUsefulService { // this is a request scoped service static scope = 'request' }
  • 7. Service Injection class ContractController { ContractService contractService ... } No need for AutoWire annotation.
  • 8. Command Objects @grails.validation.Validateable class LoginCommand { def loginService String username String password static constraints = { username validator: { val, obj -> obj.loginService.canLogin(obj.username, obj.password) } } }
  • 10. @Transactional annotation Service methods are Transactional by default. However best practice is to add @Transactional annotation to each service Transaction annotation is similar to Spring’s @Transactional annotation The @Transactional annotation on the class ensures that all public methods in a service are transactional. Annotating a service method (and not at class) with @Transactional disables the default Grails transactional behavior for that method. so if you use any annotations you must annotate all methods that require transactions.
  • 11. Example import grails.transaction.Transactional @Transactional class BookService { @Transactional(readOnly = true) def listBooks() { Book.list() } def updateBook() { // … } }
  • 12. No Transaction & ReadOnly @NonTransactional class EmailService { //OR static transactional = false …. } @Transactional(readOnly = true) class ReportService { …. }
  • 13. withTransaction package com.netflix class ContractService { // turn off automatic transaction management static transactional = false void someServiceMethod() { Contract.withTransaction {TransactionStatus tx -> // do some work with the database…. // if the transaction needs to be rolled back, call setRollbackOnly() tx.setRollbackOnly() } } }
  • 14. Savepoint def save() { Album.withTransaction { status -> def album = Album.get(params.id) album.title = "Changed Title" album.save(flush:true) def savepoint = status.createSavepoint() ... // something goes wrong if(hasSomethingGoneWrong()) { status.rollbackToSavepoint(savepoint) // do something else ... } } }
  • 15. Transaction Propagation :( // Doesn’t work well without additional configuration @Transactional void someMethod(...) { // do some work ... storeAuditData(...) } @Transactional(propagation=Propagation.REQUIRES_NEW) void storeAuditData(...) { // } http://techbus.safaribooksonline.com/book/programming/9781449324513/4dot- spring/_transactional_services_html
  • 17. Exceptions and Validations class AuthorService { void updateAge(id, int age) { def author = Author.get(id) author.age = age if (author.isTooOld()) { throw new AuthorException("too old", author) } if (!author.validate()) { throw new ValidationException("Author is not valid", author.errors) } } }
  • 18. Exception on Save def p = Person.get(1) try { p.save(failOnError: true) } catch (ValidationException e) { // deal with exception p.errors.allErrors.each { println it } }
  • 19. LazyInitializationException When a transaction is rolled back the Hibernate session used by GORM is cleared. This means any objects within the session become detached and accessing uninitialized lazy-loaded collections will lead to LazyInitializationException class AuthorController { def authorService def updateAge() { try { authorService.updateAge(params.id, params.int("age")) } catch(e) { render "Author books ${e.author.books}" } } }
  • 20. Solution... class AuthorService { void updateAge(id, int age) { def author = Author.findById(id, [fetch:[books:"eager"]]) author.age = age if (author.isTooOld()) { throw new AuthorException("too old", author) } } }
  • 22.
  • 23.
  • 25. Various ways... ● Event mechanism using Platform Core plugin ● JMS Messaging Queues Plugin ● Quartz scheduling Plugin ● Asynchronous Programming
  • 26. Asynchronous - Promise import static java.util.concurrent.TimeUnit.* import static grails.async.Promises.* Promise p = Promises.task { // Long running task } p.onError { Throwable err -> println "An error occured ${err.message}" } p.onComplete { result -> println "Promise returned $result" }
  • 27. Synchronous - Promise import static java.util.concurrent.TimeUnit.* import static grails.async.Promises.* Promise p = task { // Long running task } …. other tasks // block until result is called def result = p.get() // block for the specified time def result = p.get(1,MINUTES)
  • 28. PromiseList import static grails.async.Promises.* import grails.async.PromiseList PromiseList promiseList = tasks([{ 2 * 2 }, { 4 * 4}, { 8 * 8 }]) //... some other processes assert [4,16,64] == promiseList.get()
  • 29. PromiseMap import grails.async.* PromiseMap map = new PromiseMap() map['one'] = { 2 * 2 } map['two'] = { 4 * 4 } map['three'] = { 8 * 8 } //Async call map.onComplete { Map results -> assert [one:4,two:16,three:64] == results }
  • 30. DelegateAsync Transformation //Sync service class BookService { List<Book> findBooks(String title) { // implementation } } //Async Service import grails.async.* class AsyncBookService { @DelegateAsync BookService bookService }
  • 31. DelegateAsync call //Async service call AsyncBookService asyncBookService def findBooks(String title) { asyncBookService.findBooks(title) .onComplete { List results -> println "Books = ${results}" } }
  • 32. Asynchronous GORM import static grails.async.Promises.* Person.async.list().onComplete { List results -> println "Got people = ${results}" } PromiseList p = Person.async.getAll(1L, 2L, 3L) List results = p.get() Promise p1 = Person.async.findByFirstName("Homer") Promise p2 = Person.async.findByFirstName("Bart") Promise p3 = Person.async.findByFirstName("Barney") results = waitAll(p1, p2, p3)
  • 33. Async and the Session When using GORM async each promise is executed in a different thread. Since the Hibernate session is not concurrency safe, a new session is bound per thread. This means you cannot save objects returned from asynchronous queries without first merging them back into session. def promise = Person.async.findByFirstName("Homer") def person = promise.get() person.merge() person.firstName = "Bart" In general it is not recommended to read and write objects in different threads and you should avoid this technique unless absolutely necessary. Also fetch the dependent objects eagerly to avoid LazyInitializationException
  • 34. Quartz plugins { ... compile ":quartz:1.0.1" ... } //New commands grails create-job grails install-quartz-config grails create-job com.netflix.SupplierImport
  • 35.