SlideShare une entreprise Scribd logo
1  sur  26
Télécharger pour lire hors ligne
Implementing a many-to-many
Relationship with Slick
Implementing a many-to-many
Relationship with Slick
Author: Hermann Hueck
Source code and Slides available at:
https://github.com/hermannhueck/MusicService/tree/master/Services/MusicService-Play-Scala-Slick-NoAuth
http://de.slideshare.net/hermannhueck/implementing-a-manytomany-relationship-with-slick
Who am I?Who am I?
Hermann Hueck
Software Developer – Scala, Java, Akka, Play
https://www.xing.com/profile/Hermann_Hueck
Presentation OverviewPresentation Overview
● Short Intro to Slick
● Many-to-many Relationship with Slick –
Example: A Music Service
● Q & A
Part 1: Intro to SlickPart 1: Intro to Slick
● What is Slick?
● What is FRM (Functional Relational Mapping)?
● How to execute a database action?
● Why is it reactive?
● Short Reminder of Scala Futures
● Simple Slick Example (Activator Template: hello-slick-3.1)
● Table Definitions without and with Case Class Mapping
What is Slick?What is Slick?
The Slick manual says:
Slick (“Scala Language-Integrated Connection Kit”) is
Typesafe‘s Functional Relational Mapping (FRM) library for
Scala that makes it easy to work with relational databases. It
allows you to work with stored data almost as if you were
using Scala collections while at the same time giving you full
control over when a database access happens and which data
is transferred. You can also use SQL directly. Execution of
database actions is done asynchronously, making Slick a
perfect fit for your reactive applications based on Play and Akka.
What is FRM?What is FRM?
● FRM = Functional Relational Mapping (opposed to ORM)
● Slick allows you to process persistent relational data stored in
DB tables the same (functional) way as you do with in-memory
data, i.e. Scala collections.
● Table Queries are monads.
● Table Queries are pre-optimized.
● Table Queries are type-safe.
● The Scala compiler complains, if you specify your table query
incorrectly.
TableQuery s are Monads.TableQuery s are Monads.
● filter() for the selection of data
● map() for the projection
● flatMap() to pass the output of your 1st DB operation as input to the
2nd DB operation.
● With the provision of these three monadical functions TableQuery s
are monads.
● Hence you can also use the syntactic sugar of for-comprehensions.
● There is more. E.g. the sortBy() function allows you to define the
sort order of your query result.
How to execute a Slick DB Action?How to execute a Slick DB Action?
● Define a TableQuery
val query: Query[…] = TableQuery(…)…
● For this TableQuery, define a database action which might be a query,
insert, bulk insert, update or a delete action or even a DDL action.
val dbAction: DBIO[…] = query += record // insert
val dbAction: DBIO[…] = query ++= Seq(row0, row1, …, rowN) // bulk insert
val dbAction: DBIO[…] = query.update(valuesToUpdate) // update
val dbAction: DBIO[…] = query.delete // delete
val dbAction: DBIO[…] = query.result // insert
● Run the database action by calling db.run(dbAction). db.run never returns
the Result. You always get a Future[Result].
val dbAction: DBIO[…] = TableQuery(…).result
val future: Future[…] = db.run(dbAction)
Why is Slick reactive?Why is Slick reactive?
● It is asynchronous and non-blocking.
● It provides its own configurable thread pool.
● If you run a database action you never get the Result directly. You
always get a Future[Result].
val dbAction: DBIOAction[Seq[String]] = TableQuery(…).result
val future: Future[Seq[String]] = db.run( dbAction )
● Slick supports Reactive Streams. Hence it can easily be used together
with Akka-Streams (which is not subject of this talk).
val dbAction: StreamingDBIO[Seq[String]] = TableQuery(…).result
val publisher: DatabasePublisher[String] = db.stream( dbAction )
val source: Source = Source.fromPublisher( publisher )
// Now use the Source to construct a RunnableGraph. Then run the graph.
Short Reminder of Scala FuturesShort Reminder of Scala Futures
In Slick every database access returns a Future.
How can one async (DB) function process the result of another async
(DB) function?
This scenario happens very often when querying and manipulating
database records.
A very informative and understandable blog on Futures can be found
here:
http://danielwestheide.com/blog/2013/01/09/the-neophytes-guide-to-scala
-part-8-welcome-to-the-future.html
How to process the Result of an Async
Function by another Async Function
How to process the Result of an Async
Function by another Async Function
Using Future.flatMap:
def doAAsync(input: String): Future[A] = Future { val a = f(input); a }
def doBAsync(a: A): Future[B] = Future { val b = g(a); b }
val input = “some input“
val futureA: Future[A] = doAAsync(input)
val futureB: Future[B] = futureA flatMap { a => doBAsync(a) }
futureB.foreach { b => println(b) }
Async Function processing the
Result of another Async Function
Async Function processing the
Result of another Async Function
Using a for-comprehension:
def doAAsync(input: String): Future[A] = Future { val a = f(input); a }
def doBAsync(a: A): Future[B] = Future { val b = g(a); b }
val input = “some input“
val futureB: Future[B] = for {
a <- doAAsync(input)
b <- doBAsync(a)
} yield b
futureB.foreach { b => println(b) }
A Simple Slick ExampleA Simple Slick Example
Activator Template: hello-slick-3.1
Table Definition with a TupleTable Definition with a Tuple
class Users(tag: Tag) extends Table[(String, Option[Int])](tag, "USERS") {
// Auto Increment the id primary key column
def id = column[Int]("ID", O.PrimaryKey, O.AutoInc)
// The name can't be null
def name = column[String]("NAME", O.NotNull)
// the * projection (e.g. select * ...)
def * = (name, id.?)
}
Tuple
Table Definition with Case Class
Mapping
Table Definition with Case Class
Mapping
case class User(name: String, id: Option[Int] = None)
class Users(tag: Tag) extends Table[User](tag, "USERS") {
// Auto Increment the id primary key column
def id = column[Int]("ID", O.PrimaryKey, O.AutoInc)
// The name can't be null
def name = column[String]("NAME", O.NotNull)
// the * projection (e.g. select * ...) auto-transforms the tupled
// column values to / from a User
def * = (name, id.?) <> (User.tupled, User.unapply)
}
Map Tuple to User Map User to Tuple
Part 2: Many-to-many with SlickPart 2: Many-to-many with Slick
● The Demo App: MusicService
● Many-to-many Relationship (DB Schema)
● Web Application Demo
● Many-to-many in Slick Table Definitions
● Ensuring Referential Integrity
● Adding and Deleting Relationships
● Traversing the many-to-many Relationship in Queries
The Demo App: MusicServiceThe Demo App: MusicService
● The MusicService manages Music Recordings
and Performers.
● A Recording is performedBy many (0 … n)
Performers.
● A Performer is performingIn many (0 … n)
Recordings.
Many-to-many in the DB SchemaMany-to-many in the DB Schema
ID NAME PERFORMER_TYPE
1 Arthur Rubinstein Soloist
2 London Phil. Orch. Ensemble
3 Herbert von Karajan Conductor
4 Christopher Park Soloist
...
PERFORMERS
ID TITLE COMPOSER YEAR
1 Beethoven's Symphony No. 5 Ludwig v. Beethoven 2005
2 Forellenquintett Franz Schubert 2006
3 Eine kleine Nachtmusik Wolfgang Amadeus Mozart 2005
4 Entführung aus dem Serail Wolfgang Amadeus Mozart 2008
...
RECORDINGS
REC_ID PER_ID
1 1
1 2
1 3
3 1
... ...
RECORDINGS_PERFORMERS
Web Application DemoWeb Application Demo
MusicService is a Play Application with a rather primitive
UI. This interface allows the user to …
● Create, delete, update Performers and Recordings
● Assign Performers to Recordings or Recordings to
Performers and delete these Assignments
● Query / Search for Performers and Recordings
● Play Recordings
Many-to-many Relationship in the
Slick Table Definitions
Many-to-many Relationship in the
Slick Table Definitions
case class RecordingPerformer(recId: Long, perId: Long)
// Table 'RecordingsPerformers' mapped to case class 'RecordingPerformer' as join table to map
// the many-to-many relationship between Performers and Recordings
//
class RecordingsPerformers(tag: Tag)
extends Table[RecordingPerformer](tag, "RECORDINGS_PERFORMERS") {
def recId: Rep[Long] = column[Long]("REC_ID")
def perId: Rep[Long] = column[Long]("PER_ID")
def * = (recId, perId) <> (RecordingPerformer.tupled, RecordingPerformer.unapply)
def pk = primaryKey("primaryKey", (recId, perId))
def recFK = foreignKey("FK_RECORDINGS", recId, TableQuery[Recordings])(recording =>
recording.id, onDelete=ForeignKeyAction.Cascade)
def perFK = foreignKey("FK_PERFORMERS", perId, TableQuery[Performers])(performer =>
performer.id)
// onUpdate=ForeignKeyAction.Restrict is omitted as this is the default
}
Ensuring Referential IntegrityEnsuring Referential Integrity
● Referential Integrity is guaranteed by the definition of a foreignKey()
function in the referring table, which allows to navigate to the referred
table.
● You can optionally specify an onDelete action and an onUpdate
action, which has one of the following values:
 ForeignKeyAction.NoAction
 ForeignKeyAction.Restrict
 ForeignKeyAction.Cascade
 ForeignKeyAction.SetNull
 ForeignKeyAction.SetDefault
Adding and Deleting RelationshipsAdding and Deleting Relationships
● Adding a concrete relationship == Adding an
entry into the Mapping Table, if it doesn't
already exist.
● Deleting a concrete relationship == Deleting an
entry from the Mapping Table, if it exists.
● Updates in the Mapping Table do not make
much sense. Hence I do not support them im
my implementation.
Traversing many-to-many the
Relationship in Queries
Traversing many-to-many the
Relationship in Queries
● The Query.join() function allows you to perform an inner
join on tables.
● The Query.on() function allows you to perform an inner
join on tables.
● Example:
val query = TableQuery[Performers] join TableQuery[RecordingsPerformers] on (_.id === _.perId)
val future: Future[Seq[(Performer, RecordingPerformer)]] = db.run { query.result }
// Now postprocess this future with filter, map, flatMap etc.
// Especially filter the result for a specific recording id.
Thank you for listening!
Q & A
ResourcesResources
● Slick Website:
http://slick.typesafe.com/doc/3.1.1/
● Slick Activator Template Website with Tutorial:
https://www.typesafe.com/activator/template/hello-slick-3.1
● Slick Activator Template Source Code:
https://github.com/typesafehub/activator-hello-slick#slick-3.1
● A very informative blog on Futures:
http://danielwestheide.com/blog/2013/01/09/the-neophytes-guide-to-scala-part-8-welcome-to-the-
future.html
● MusicService Source Code and Slides at Github:
https://github.com/hermannhueck/MusicService/tree/master/Services/MusicService-Play-Scala-S
lick-NoAuth
● MusicService Slides at SlideShare:
http://de.slideshare.net/hermannhueck/implementing-a-manytomany-relationship-with-slick
● Authors XING Profile:
https://www.xing.com/profile/Hermann_Hueck

Contenu connexe

En vedette

Slick - The Structured Way
Slick - The Structured WaySlick - The Structured Way
Slick - The Structured WayYennick Trevels
 
Slick: Bringing Scala’s Powerful Features to Your Database Access
Slick: Bringing Scala’s Powerful Features to Your Database Access Slick: Bringing Scala’s Powerful Features to Your Database Access
Slick: Bringing Scala’s Powerful Features to Your Database Access Rebecca Grenier
 
Patterns for slick database applications
Patterns for slick database applicationsPatterns for slick database applications
Patterns for slick database applicationsSkills Matter
 
A Deeper Look Into Reactive Streams with Akka Streams 1.0 and Slick 3.0
A Deeper Look Into Reactive Streams with Akka Streams 1.0 and Slick 3.0A Deeper Look Into Reactive Streams with Akka Streams 1.0 and Slick 3.0
A Deeper Look Into Reactive Streams with Akka Streams 1.0 and Slick 3.0Legacy Typesafe (now Lightbend)
 
Reactive database access with Slick3
Reactive database access with Slick3Reactive database access with Slick3
Reactive database access with Slick3takezoe
 
Play Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and ScalaPlay Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and ScalaYevgeniy Brikman
 
バッチを Akka Streams で再実装したら100倍速くなった話 #ScalaMatsuri
バッチを Akka Streams で再実装したら100倍速くなった話 #ScalaMatsuriバッチを Akka Streams で再実装したら100倍速くなった話 #ScalaMatsuri
バッチを Akka Streams で再実装したら100倍速くなった話 #ScalaMatsuriKazuki Negoro
 
the evolution of data infrastructure at lianjia
the evolution of data infrastructure at lianjiathe evolution of data infrastructure at lianjia
the evolution of data infrastructure at lianjia毅 吕
 

En vedette (8)

Slick - The Structured Way
Slick - The Structured WaySlick - The Structured Way
Slick - The Structured Way
 
Slick: Bringing Scala’s Powerful Features to Your Database Access
Slick: Bringing Scala’s Powerful Features to Your Database Access Slick: Bringing Scala’s Powerful Features to Your Database Access
Slick: Bringing Scala’s Powerful Features to Your Database Access
 
Patterns for slick database applications
Patterns for slick database applicationsPatterns for slick database applications
Patterns for slick database applications
 
A Deeper Look Into Reactive Streams with Akka Streams 1.0 and Slick 3.0
A Deeper Look Into Reactive Streams with Akka Streams 1.0 and Slick 3.0A Deeper Look Into Reactive Streams with Akka Streams 1.0 and Slick 3.0
A Deeper Look Into Reactive Streams with Akka Streams 1.0 and Slick 3.0
 
Reactive database access with Slick3
Reactive database access with Slick3Reactive database access with Slick3
Reactive database access with Slick3
 
Play Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and ScalaPlay Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and Scala
 
バッチを Akka Streams で再実装したら100倍速くなった話 #ScalaMatsuri
バッチを Akka Streams で再実装したら100倍速くなった話 #ScalaMatsuriバッチを Akka Streams で再実装したら100倍速くなった話 #ScalaMatsuri
バッチを Akka Streams で再実装したら100倍速くなった話 #ScalaMatsuri
 
the evolution of data infrastructure at lianjia
the evolution of data infrastructure at lianjiathe evolution of data infrastructure at lianjia
the evolution of data infrastructure at lianjia
 

Similaire à Implementing a many-to-many Relationship with Slick

A Recovering Java Developer Learns to Go
A Recovering Java Developer Learns to GoA Recovering Java Developer Learns to Go
A Recovering Java Developer Learns to GoMatt Stine
 
Talk - Query monad
Talk - Query monad Talk - Query monad
Talk - Query monad Fabernovel
 
PofEAA and SQLAlchemy
PofEAA and SQLAlchemyPofEAA and SQLAlchemy
PofEAA and SQLAlchemyInada Naoki
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with ClojureDmitry Buzdin
 
Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)Jonathan Felch
 
Seattle useR Group - R + Scala
Seattle useR Group - R + ScalaSeattle useR Group - R + Scala
Seattle useR Group - R + ScalaShouheng Yi
 
The GO Language : From Beginners to Gophers
The GO Language : From Beginners to GophersThe GO Language : From Beginners to Gophers
The GO Language : From Beginners to GophersAlessandro Sanino
 
Emerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the HorizonEmerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the HorizonAlex Payne
 
r,rstats,r language,r packages
r,rstats,r language,r packagesr,rstats,r language,r packages
r,rstats,r language,r packagesAjay Ohri
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
20230721_OKC_Meetup_MuleSoft.pptx
20230721_OKC_Meetup_MuleSoft.pptx20230721_OKC_Meetup_MuleSoft.pptx
20230721_OKC_Meetup_MuleSoft.pptxDianeKesler1
 
Things about Functional JavaScript
Things about Functional JavaScriptThings about Functional JavaScript
Things about Functional JavaScriptChengHui Weng
 
JavaCro 2014 Scala and Java EE 7 Development Experiences
JavaCro 2014 Scala and Java EE 7 Development ExperiencesJavaCro 2014 Scala and Java EE 7 Development Experiences
JavaCro 2014 Scala and Java EE 7 Development ExperiencesPeter Pilgrim
 
Presto anatomy
Presto anatomyPresto anatomy
Presto anatomyDongmin Yu
 
A brief introduction to PostgreSQL
A brief introduction to PostgreSQLA brief introduction to PostgreSQL
A brief introduction to PostgreSQLVu Hung Nguyen
 
Exploring Clojurescript
Exploring ClojurescriptExploring Clojurescript
Exploring ClojurescriptLuke Donnet
 

Similaire à Implementing a many-to-many Relationship with Slick (20)

A Recovering Java Developer Learns to Go
A Recovering Java Developer Learns to GoA Recovering Java Developer Learns to Go
A Recovering Java Developer Learns to Go
 
Talk - Query monad
Talk - Query monad Talk - Query monad
Talk - Query monad
 
PofEAA and SQLAlchemy
PofEAA and SQLAlchemyPofEAA and SQLAlchemy
PofEAA and SQLAlchemy
 
Lobos Introduction
Lobos IntroductionLobos Introduction
Lobos Introduction
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)
 
Seattle useR Group - R + Scala
Seattle useR Group - R + ScalaSeattle useR Group - R + Scala
Seattle useR Group - R + Scala
 
Pune Clojure Course Outline
Pune Clojure Course OutlinePune Clojure Course Outline
Pune Clojure Course Outline
 
The GO Language : From Beginners to Gophers
The GO Language : From Beginners to GophersThe GO Language : From Beginners to Gophers
The GO Language : From Beginners to Gophers
 
Emerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the HorizonEmerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the Horizon
 
r,rstats,r language,r packages
r,rstats,r language,r packagesr,rstats,r language,r packages
r,rstats,r language,r packages
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
Clojure And Swing
Clojure And SwingClojure And Swing
Clojure And Swing
 
20230721_OKC_Meetup_MuleSoft.pptx
20230721_OKC_Meetup_MuleSoft.pptx20230721_OKC_Meetup_MuleSoft.pptx
20230721_OKC_Meetup_MuleSoft.pptx
 
Things about Functional JavaScript
Things about Functional JavaScriptThings about Functional JavaScript
Things about Functional JavaScript
 
JavaCro'14 - Scala and Java EE 7 Development Experiences – Peter Pilgrim
JavaCro'14 - Scala and Java EE 7 Development Experiences – Peter PilgrimJavaCro'14 - Scala and Java EE 7 Development Experiences – Peter Pilgrim
JavaCro'14 - Scala and Java EE 7 Development Experiences – Peter Pilgrim
 
JavaCro 2014 Scala and Java EE 7 Development Experiences
JavaCro 2014 Scala and Java EE 7 Development ExperiencesJavaCro 2014 Scala and Java EE 7 Development Experiences
JavaCro 2014 Scala and Java EE 7 Development Experiences
 
Presto anatomy
Presto anatomyPresto anatomy
Presto anatomy
 
A brief introduction to PostgreSQL
A brief introduction to PostgreSQLA brief introduction to PostgreSQL
A brief introduction to PostgreSQL
 
Exploring Clojurescript
Exploring ClojurescriptExploring Clojurescript
Exploring Clojurescript
 

Plus de Hermann Hueck

What's new in Scala 2.13?
What's new in Scala 2.13?What's new in Scala 2.13?
What's new in Scala 2.13?Hermann Hueck
 
Implementing the IO Monad in Scala
Implementing the IO Monad in ScalaImplementing the IO Monad in Scala
Implementing the IO Monad in ScalaHermann Hueck
 
Future vs. Monix Task
Future vs. Monix TaskFuture vs. Monix Task
Future vs. Monix TaskHermann Hueck
 
Use Applicative where applicable!
Use Applicative where applicable!Use Applicative where applicable!
Use Applicative where applicable!Hermann Hueck
 
From Function1#apply to Kleisli
From Function1#apply to KleisliFrom Function1#apply to Kleisli
From Function1#apply to KleisliHermann Hueck
 
Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)Hermann Hueck
 
From Functor Composition to Monad Transformers
From Functor Composition to Monad TransformersFrom Functor Composition to Monad Transformers
From Functor Composition to Monad TransformersHermann Hueck
 
Type Classes in Scala and Haskell
Type Classes in Scala and HaskellType Classes in Scala and Haskell
Type Classes in Scala and HaskellHermann Hueck
 
Reactive Access to MongoDB from Java 8
Reactive Access to MongoDB from Java 8Reactive Access to MongoDB from Java 8
Reactive Access to MongoDB from Java 8Hermann Hueck
 

Plus de Hermann Hueck (11)

A Taste of Dotty
A Taste of DottyA Taste of Dotty
A Taste of Dotty
 
What's new in Scala 2.13?
What's new in Scala 2.13?What's new in Scala 2.13?
What's new in Scala 2.13?
 
Pragmatic sbt
Pragmatic sbtPragmatic sbt
Pragmatic sbt
 
Implementing the IO Monad in Scala
Implementing the IO Monad in ScalaImplementing the IO Monad in Scala
Implementing the IO Monad in Scala
 
Future vs. Monix Task
Future vs. Monix TaskFuture vs. Monix Task
Future vs. Monix Task
 
Use Applicative where applicable!
Use Applicative where applicable!Use Applicative where applicable!
Use Applicative where applicable!
 
From Function1#apply to Kleisli
From Function1#apply to KleisliFrom Function1#apply to Kleisli
From Function1#apply to Kleisli
 
Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)
 
From Functor Composition to Monad Transformers
From Functor Composition to Monad TransformersFrom Functor Composition to Monad Transformers
From Functor Composition to Monad Transformers
 
Type Classes in Scala and Haskell
Type Classes in Scala and HaskellType Classes in Scala and Haskell
Type Classes in Scala and Haskell
 
Reactive Access to MongoDB from Java 8
Reactive Access to MongoDB from Java 8Reactive Access to MongoDB from Java 8
Reactive Access to MongoDB from Java 8
 

Dernier

Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxRTS corp
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolsosttopstonverter
 
Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogueitservices996
 
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesAmazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesKrzysztofKkol1
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorTier1 app
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLionel Briand
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingShane Coughlan
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITmanoharjgpsolutions
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?Alexandre Beguel
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsJean Silva
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Developmentvyaparkranti
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slidesvaideheekore1
 
SoftTeco - Software Development Company Profile
SoftTeco - Software Development Company ProfileSoftTeco - Software Development Company Profile
SoftTeco - Software Development Company Profileakrivarotava
 

Dernier (20)

Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration tools
 
Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogue
 
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesAmazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryError
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and Repair
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh IT
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero results
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Development
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slides
 
SoftTeco - Software Development Company Profile
SoftTeco - Software Development Company ProfileSoftTeco - Software Development Company Profile
SoftTeco - Software Development Company Profile
 

Implementing a many-to-many Relationship with Slick

  • 1. Implementing a many-to-many Relationship with Slick Implementing a many-to-many Relationship with Slick Author: Hermann Hueck Source code and Slides available at: https://github.com/hermannhueck/MusicService/tree/master/Services/MusicService-Play-Scala-Slick-NoAuth http://de.slideshare.net/hermannhueck/implementing-a-manytomany-relationship-with-slick
  • 2. Who am I?Who am I? Hermann Hueck Software Developer – Scala, Java, Akka, Play https://www.xing.com/profile/Hermann_Hueck
  • 3. Presentation OverviewPresentation Overview ● Short Intro to Slick ● Many-to-many Relationship with Slick – Example: A Music Service ● Q & A
  • 4. Part 1: Intro to SlickPart 1: Intro to Slick ● What is Slick? ● What is FRM (Functional Relational Mapping)? ● How to execute a database action? ● Why is it reactive? ● Short Reminder of Scala Futures ● Simple Slick Example (Activator Template: hello-slick-3.1) ● Table Definitions without and with Case Class Mapping
  • 5. What is Slick?What is Slick? The Slick manual says: Slick (“Scala Language-Integrated Connection Kit”) is Typesafe‘s Functional Relational Mapping (FRM) library for Scala that makes it easy to work with relational databases. It allows you to work with stored data almost as if you were using Scala collections while at the same time giving you full control over when a database access happens and which data is transferred. You can also use SQL directly. Execution of database actions is done asynchronously, making Slick a perfect fit for your reactive applications based on Play and Akka.
  • 6. What is FRM?What is FRM? ● FRM = Functional Relational Mapping (opposed to ORM) ● Slick allows you to process persistent relational data stored in DB tables the same (functional) way as you do with in-memory data, i.e. Scala collections. ● Table Queries are monads. ● Table Queries are pre-optimized. ● Table Queries are type-safe. ● The Scala compiler complains, if you specify your table query incorrectly.
  • 7. TableQuery s are Monads.TableQuery s are Monads. ● filter() for the selection of data ● map() for the projection ● flatMap() to pass the output of your 1st DB operation as input to the 2nd DB operation. ● With the provision of these three monadical functions TableQuery s are monads. ● Hence you can also use the syntactic sugar of for-comprehensions. ● There is more. E.g. the sortBy() function allows you to define the sort order of your query result.
  • 8. How to execute a Slick DB Action?How to execute a Slick DB Action? ● Define a TableQuery val query: Query[…] = TableQuery(…)… ● For this TableQuery, define a database action which might be a query, insert, bulk insert, update or a delete action or even a DDL action. val dbAction: DBIO[…] = query += record // insert val dbAction: DBIO[…] = query ++= Seq(row0, row1, …, rowN) // bulk insert val dbAction: DBIO[…] = query.update(valuesToUpdate) // update val dbAction: DBIO[…] = query.delete // delete val dbAction: DBIO[…] = query.result // insert ● Run the database action by calling db.run(dbAction). db.run never returns the Result. You always get a Future[Result]. val dbAction: DBIO[…] = TableQuery(…).result val future: Future[…] = db.run(dbAction)
  • 9. Why is Slick reactive?Why is Slick reactive? ● It is asynchronous and non-blocking. ● It provides its own configurable thread pool. ● If you run a database action you never get the Result directly. You always get a Future[Result]. val dbAction: DBIOAction[Seq[String]] = TableQuery(…).result val future: Future[Seq[String]] = db.run( dbAction ) ● Slick supports Reactive Streams. Hence it can easily be used together with Akka-Streams (which is not subject of this talk). val dbAction: StreamingDBIO[Seq[String]] = TableQuery(…).result val publisher: DatabasePublisher[String] = db.stream( dbAction ) val source: Source = Source.fromPublisher( publisher ) // Now use the Source to construct a RunnableGraph. Then run the graph.
  • 10. Short Reminder of Scala FuturesShort Reminder of Scala Futures In Slick every database access returns a Future. How can one async (DB) function process the result of another async (DB) function? This scenario happens very often when querying and manipulating database records. A very informative and understandable blog on Futures can be found here: http://danielwestheide.com/blog/2013/01/09/the-neophytes-guide-to-scala -part-8-welcome-to-the-future.html
  • 11. How to process the Result of an Async Function by another Async Function How to process the Result of an Async Function by another Async Function Using Future.flatMap: def doAAsync(input: String): Future[A] = Future { val a = f(input); a } def doBAsync(a: A): Future[B] = Future { val b = g(a); b } val input = “some input“ val futureA: Future[A] = doAAsync(input) val futureB: Future[B] = futureA flatMap { a => doBAsync(a) } futureB.foreach { b => println(b) }
  • 12. Async Function processing the Result of another Async Function Async Function processing the Result of another Async Function Using a for-comprehension: def doAAsync(input: String): Future[A] = Future { val a = f(input); a } def doBAsync(a: A): Future[B] = Future { val b = g(a); b } val input = “some input“ val futureB: Future[B] = for { a <- doAAsync(input) b <- doBAsync(a) } yield b futureB.foreach { b => println(b) }
  • 13. A Simple Slick ExampleA Simple Slick Example Activator Template: hello-slick-3.1
  • 14. Table Definition with a TupleTable Definition with a Tuple class Users(tag: Tag) extends Table[(String, Option[Int])](tag, "USERS") { // Auto Increment the id primary key column def id = column[Int]("ID", O.PrimaryKey, O.AutoInc) // The name can't be null def name = column[String]("NAME", O.NotNull) // the * projection (e.g. select * ...) def * = (name, id.?) } Tuple
  • 15. Table Definition with Case Class Mapping Table Definition with Case Class Mapping case class User(name: String, id: Option[Int] = None) class Users(tag: Tag) extends Table[User](tag, "USERS") { // Auto Increment the id primary key column def id = column[Int]("ID", O.PrimaryKey, O.AutoInc) // The name can't be null def name = column[String]("NAME", O.NotNull) // the * projection (e.g. select * ...) auto-transforms the tupled // column values to / from a User def * = (name, id.?) <> (User.tupled, User.unapply) } Map Tuple to User Map User to Tuple
  • 16. Part 2: Many-to-many with SlickPart 2: Many-to-many with Slick ● The Demo App: MusicService ● Many-to-many Relationship (DB Schema) ● Web Application Demo ● Many-to-many in Slick Table Definitions ● Ensuring Referential Integrity ● Adding and Deleting Relationships ● Traversing the many-to-many Relationship in Queries
  • 17. The Demo App: MusicServiceThe Demo App: MusicService ● The MusicService manages Music Recordings and Performers. ● A Recording is performedBy many (0 … n) Performers. ● A Performer is performingIn many (0 … n) Recordings.
  • 18. Many-to-many in the DB SchemaMany-to-many in the DB Schema ID NAME PERFORMER_TYPE 1 Arthur Rubinstein Soloist 2 London Phil. Orch. Ensemble 3 Herbert von Karajan Conductor 4 Christopher Park Soloist ... PERFORMERS ID TITLE COMPOSER YEAR 1 Beethoven's Symphony No. 5 Ludwig v. Beethoven 2005 2 Forellenquintett Franz Schubert 2006 3 Eine kleine Nachtmusik Wolfgang Amadeus Mozart 2005 4 Entführung aus dem Serail Wolfgang Amadeus Mozart 2008 ... RECORDINGS REC_ID PER_ID 1 1 1 2 1 3 3 1 ... ... RECORDINGS_PERFORMERS
  • 19. Web Application DemoWeb Application Demo MusicService is a Play Application with a rather primitive UI. This interface allows the user to … ● Create, delete, update Performers and Recordings ● Assign Performers to Recordings or Recordings to Performers and delete these Assignments ● Query / Search for Performers and Recordings ● Play Recordings
  • 20. Many-to-many Relationship in the Slick Table Definitions Many-to-many Relationship in the Slick Table Definitions case class RecordingPerformer(recId: Long, perId: Long) // Table 'RecordingsPerformers' mapped to case class 'RecordingPerformer' as join table to map // the many-to-many relationship between Performers and Recordings // class RecordingsPerformers(tag: Tag) extends Table[RecordingPerformer](tag, "RECORDINGS_PERFORMERS") { def recId: Rep[Long] = column[Long]("REC_ID") def perId: Rep[Long] = column[Long]("PER_ID") def * = (recId, perId) <> (RecordingPerformer.tupled, RecordingPerformer.unapply) def pk = primaryKey("primaryKey", (recId, perId)) def recFK = foreignKey("FK_RECORDINGS", recId, TableQuery[Recordings])(recording => recording.id, onDelete=ForeignKeyAction.Cascade) def perFK = foreignKey("FK_PERFORMERS", perId, TableQuery[Performers])(performer => performer.id) // onUpdate=ForeignKeyAction.Restrict is omitted as this is the default }
  • 21. Ensuring Referential IntegrityEnsuring Referential Integrity ● Referential Integrity is guaranteed by the definition of a foreignKey() function in the referring table, which allows to navigate to the referred table. ● You can optionally specify an onDelete action and an onUpdate action, which has one of the following values:  ForeignKeyAction.NoAction  ForeignKeyAction.Restrict  ForeignKeyAction.Cascade  ForeignKeyAction.SetNull  ForeignKeyAction.SetDefault
  • 22. Adding and Deleting RelationshipsAdding and Deleting Relationships ● Adding a concrete relationship == Adding an entry into the Mapping Table, if it doesn't already exist. ● Deleting a concrete relationship == Deleting an entry from the Mapping Table, if it exists. ● Updates in the Mapping Table do not make much sense. Hence I do not support them im my implementation.
  • 23. Traversing many-to-many the Relationship in Queries Traversing many-to-many the Relationship in Queries ● The Query.join() function allows you to perform an inner join on tables. ● The Query.on() function allows you to perform an inner join on tables. ● Example: val query = TableQuery[Performers] join TableQuery[RecordingsPerformers] on (_.id === _.perId) val future: Future[Seq[(Performer, RecordingPerformer)]] = db.run { query.result } // Now postprocess this future with filter, map, flatMap etc. // Especially filter the result for a specific recording id.
  • 24. Thank you for listening!
  • 25. Q & A
  • 26. ResourcesResources ● Slick Website: http://slick.typesafe.com/doc/3.1.1/ ● Slick Activator Template Website with Tutorial: https://www.typesafe.com/activator/template/hello-slick-3.1 ● Slick Activator Template Source Code: https://github.com/typesafehub/activator-hello-slick#slick-3.1 ● A very informative blog on Futures: http://danielwestheide.com/blog/2013/01/09/the-neophytes-guide-to-scala-part-8-welcome-to-the- future.html ● MusicService Source Code and Slides at Github: https://github.com/hermannhueck/MusicService/tree/master/Services/MusicService-Play-Scala-S lick-NoAuth ● MusicService Slides at SlideShare: http://de.slideshare.net/hermannhueck/implementing-a-manytomany-relationship-with-slick ● Authors XING Profile: https://www.xing.com/profile/Hermann_Hueck