SlideShare ist ein Scribd-Unternehmen logo
1 von 26
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

Europython 2011 - Playing tasks with Django & Celery
Europython 2011 - Playing tasks with Django & CeleryEuropython 2011 - Playing tasks with Django & Celery
Europython 2011 - Playing tasks with Django & Celery
Mauro Rocco
 

Was ist angesagt? (20)

Best Practices for Middleware and Integration Architecture Modernization with...
Best Practices for Middleware and Integration Architecture Modernization with...Best Practices for Middleware and Integration Architecture Modernization with...
Best Practices for Middleware and Integration Architecture Modernization with...
 
Introduction to PySpark
Introduction to PySparkIntroduction to PySpark
Introduction to PySpark
 
Europython 2011 - Playing tasks with Django & Celery
Europython 2011 - Playing tasks with Django & CeleryEuropython 2011 - Playing tasks with Django & Celery
Europython 2011 - Playing tasks with Django & Celery
 
Data Source API in Spark
Data Source API in SparkData Source API in Spark
Data Source API in Spark
 
Productizing Structured Streaming Jobs
Productizing Structured Streaming JobsProductizing Structured Streaming Jobs
Productizing Structured Streaming Jobs
 
Introducing DataFrames in Spark for Large Scale Data Science
Introducing DataFrames in Spark for Large Scale Data ScienceIntroducing DataFrames in Spark for Large Scale Data Science
Introducing DataFrames in Spark for Large Scale Data Science
 
A Brief Intro to Scala
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to Scala
 
[DSC Adria 23] Mikhail Rozhkov DVC in Machine Learning Engineering and MLOps ...
[DSC Adria 23] Mikhail Rozhkov DVC in Machine Learning Engineering and MLOps ...[DSC Adria 23] Mikhail Rozhkov DVC in Machine Learning Engineering and MLOps ...
[DSC Adria 23] Mikhail Rozhkov DVC in Machine Learning Engineering and MLOps ...
 
Building RESTful applications using Spring MVC
Building RESTful applications using Spring MVCBuilding RESTful applications using Spring MVC
Building RESTful applications using Spring MVC
 
Programación Funcional 101 con Scala y ZIO 2.0
Programación Funcional 101 con Scala y ZIO 2.0Programación Funcional 101 con Scala y ZIO 2.0
Programación Funcional 101 con Scala y ZIO 2.0
 
A Deep Dive into Spark SQL's Catalyst Optimizer with Yin Huai
A Deep Dive into Spark SQL's Catalyst Optimizer with Yin HuaiA Deep Dive into Spark SQL's Catalyst Optimizer with Yin Huai
A Deep Dive into Spark SQL's Catalyst Optimizer with Yin Huai
 
What No One Tells You About Writing a Streaming App: Spark Summit East talk b...
What No One Tells You About Writing a Streaming App: Spark Summit East talk b...What No One Tells You About Writing a Streaming App: Spark Summit East talk b...
What No One Tells You About Writing a Streaming App: Spark Summit East talk b...
 
Learn Apache Spark: A Comprehensive Guide
Learn Apache Spark: A Comprehensive GuideLearn Apache Spark: A Comprehensive Guide
Learn Apache Spark: A Comprehensive Guide
 
Pyspark Tutorial | Introduction to Apache Spark with Python | PySpark Trainin...
Pyspark Tutorial | Introduction to Apache Spark with Python | PySpark Trainin...Pyspark Tutorial | Introduction to Apache Spark with Python | PySpark Trainin...
Pyspark Tutorial | Introduction to Apache Spark with Python | PySpark Trainin...
 
Algebraic Data Types for Data Oriented Programming - From Haskell and Scala t...
Algebraic Data Types forData Oriented Programming - From Haskell and Scala t...Algebraic Data Types forData Oriented Programming - From Haskell and Scala t...
Algebraic Data Types for Data Oriented Programming - From Haskell and Scala t...
 
PySpark dataframe
PySpark dataframePySpark dataframe
PySpark dataframe
 
A Tale of Three Apache Spark APIs: RDDs, DataFrames, and Datasets with Jules ...
A Tale of Three Apache Spark APIs: RDDs, DataFrames, and Datasets with Jules ...A Tale of Three Apache Spark APIs: RDDs, DataFrames, and Datasets with Jules ...
A Tale of Three Apache Spark APIs: RDDs, DataFrames, and Datasets with Jules ...
 
Apache doris (incubating) introduction
Apache doris (incubating) introductionApache doris (incubating) introduction
Apache doris (incubating) introduction
 
Learn flask in 90mins
Learn flask in 90minsLearn flask in 90mins
Learn flask in 90mins
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
 

Andere mochten auch

Introduction of Lianjia China
Introduction of Lianjia ChinaIntroduction of Lianjia China
Introduction of Lianjia China
Gabriel Shen
 
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
Legacy Typesafe (now Lightbend)
 
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
毅 吕
 

Andere mochten auch (13)

Using Scala Slick at FortyTwo
Using Scala Slick at FortyTwoUsing Scala Slick at FortyTwo
Using Scala Slick at FortyTwo
 
Draw More, Work Less
Draw More, Work LessDraw More, Work Less
Draw More, Work Less
 
Sharing Sensitive Data With Confidence: The DataTags system
Sharing Sensitive Data With Confidence: The DataTags systemSharing Sensitive Data With Confidence: The DataTags system
Sharing Sensitive Data With Confidence: The DataTags system
 
Introduction of Lianjia China
Introduction of Lianjia ChinaIntroduction of Lianjia China
Introduction of Lianjia China
 
Reactive Access to MongoDB from Scala
Reactive Access to MongoDB from ScalaReactive Access to MongoDB from Scala
Reactive Access to MongoDB from Scala
 
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
 

Ähnlich wie Implementing a many-to-many Relationship with Slick

PofEAA and SQLAlchemy
PofEAA and SQLAlchemyPofEAA and SQLAlchemy
PofEAA and SQLAlchemy
Inada Naoki
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
Dmitry Buzdin
 
r,rstats,r language,r packages
r,rstats,r language,r packagesr,rstats,r language,r packages
r,rstats,r language,r packages
Ajay Ohri
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
David Padbury
 
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
HUJAK - Hrvatska udruga Java korisnika / Croatian Java User Association
 
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
Peter Pilgrim
 

Ähnlich wie 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
 

Mehr von Hermann Hueck

Mehr von 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
 

Kürzlich hochgeladen

introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Kürzlich hochgeladen (20)

Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 

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