SlideShare uma empresa Scribd logo
1 de 31
Scala Language Integrated Connection
Kit(1.0.1)
Satendra Kumar
Software Consultant
Knoldus Software LLP
Topics Covered
What is Slick
Slick Key Features
Quick Overview
Live Demo
What is Slick
for{e ← Employees} yield e

“select * from employee”

●

Slick is a library written in scala for taking to database from scala programs.

●

It is currently based on Jdbc.

●

It is Successor of ScalaQuery.

●

Developed By Typesafe and EPFL(École Polytechnique Fédérale de Lausanne)
Slick's API
●

Lifted embedding
- The lifted embedding is Slick's stable query API which is based on ScalaQuery.

●

Direct embedding
- The direct embedding is a new experimental API for Slick that uses macros to
allow expressions operating on standard Scala types to be used for database
queries

●

Plain SQL
- Slick also allows you to write your own SQL queries and execute them with an
API which is optimized for Scala, much easier to use and more concise than
JDBC.
Supported Databases
●

PostgreSQL

●

MySQL

●

H2

●

Hsqldb

●

Derby/JavaDB

●

SQL Server

●

SQLite

●

Access

●

Oracle

●

DB2
* All green color database driver are open source
* All yellow color database driver are not open source.( commercially supported by Typesafe)
Slick Key Features
●

Easy

●

Concise

●

Safe

●

Composable

●

Explicit
Easy
●

Access stored data just like Scala collections.
- for{ e ← Emp if( p.age === 25 )} yield e

●

Unified session management based on JDBC Connections
-forURL(url: String, user: String = null, password: String = null, prop:
Properties = null, driver: String = null): Database
- database.withSession{ // put code here }

●

Supports SQL if you need it

●

Simple setup
Concise
●

Slick uses scala syntax.

●

Fetch results without pain
- [jdbc] val sql = "select * from employee where name = ?“
val st = conn.prepareStatement( sql )
try {
st.setString(1, name)
val rs = st.executeQuery()
val b = new ListBuffer[(Int, String)]
while(rs.next)
b.append((rs.getInt(1), rs.getString(2)))
b.toList
} finally st.close()
- [slick]( for( e <- Epmloyees if e.name === name ) yield e).list
Safe
●

No SQL-injections

●

Compile-time safety (types, names, no typos, etc.)
-[jdbc] "select

* from employee wehres nami = ' " + name + " ' "

-[slick]for( e <- Employees if e.name === name ) yield e
●

Type-safe use of stored procedures
val getfeedbackByQuestionId =
SimpleFunction.unary[ Int,String] ("getfeedbackbyquestionid")
Composable
Projects

Employees

*
*
EmpProjects
●

def employeeByJoiningDate( from:Date, to:Date ) = Employees.filter(
emp => emp.joiningDate >= from && emp.joiningDate <= to )
// projects with employee name (joining between 1-1-2013 and 1-10-2013)
for{ emp <- employeeByJoiningDate(1-1-2013, 1-10-2013)
empproject <- EmpProjects if (emp.id === empproject.empId)
project <- Projects if (empproject.projectId === project.id)
} yield (emp.name, project.name, project.location)
Explicit
●

No lazy loading means predictable performance.

●

Only read the data you need.

●

State less
- no caches
Overview
Accessing databases using Slick’s lifted embedding requires the following
steps: 1. Add the dependencies
2. Pick a driver for a particular database
3. Database Connection
- Database object
- Session
5. Describe Database schema
6. Write queries
* In this presentation we are using postgres database.
Dependencies
Add dependencies in your build.sbt
libraryDependencies ++= List(
"com.typesafe.slick" %% "slick" % "1.0.1",
"org.slf4j" % "slf4j-nop" % "1.6.4",
"postgresql" % "postgresql" % "9.1-901.jdbc4"
)

- Slick uses SLF4J for its own debug logging so you also need to add an SLF4J
implementation. Here we are using slf4j-nop to disable logging.

- You have to replace this with a real logging framework like Logback if you want to see
log output
Database drive
Import database drive :
// for postgres database
●

import scala.slick.driver.PostgresDriver.simple._
- Since we are using postgres as our database system, we need to import features from
Slick’s PostgresDriver. A driver’s simple object contains all commonly needed imports
from the driver and other parts of Slick such as session handling.
Database object
Factory methods for creating Database objects:
●

def forDataSource(ds: DataSource): Database
- Create a Database based on a DataSource.

●

def forName(name: String): Database
- Create a Database based on the JNDI name of a DataSource.

●

def forDriver(driver: Driver, url: String, user: String = null, password: String = null,
prop: Properties = null): Database
- Create a Database that directly uses a Driver to open new connections. This is needed to open a

JDBC URL with a driver that was not loaded by the system ClassLoader.
●

def forURL(url: String, user: String = null, password: String = null, prop: Properties
= null, driver: String = null): Database
- Create a Database that uses the DriverManager to open new connections.
Session
A database instance to which connections can be created. Encapsulates either a DataSource
or parameters for DriverManager.getConnection().
Methods for session creation:
def createSession(): Session
- Create a new session. The session needs to be closed explicitly by calling its close()
method.
def withSession[T](f: (Session) ⇒ T): T
- Run the supplied function with a new session and automatically close the session at
the end.
def withTransaction[T](f: (Session) ⇒ T): T
- Run the supplied function with a new session in a transaction and automatically close the
session at the end.
Example
Get database object:
val dbObject = Database.forURL("jdbc:postgresql://localhost:5432/slickdemo", "sky",
"satendra", null, "org.postgresql.Driver")
Get Session:
dbObject.withSession{ implicit session: Session =>
// write query here
}
* End of block session closed automatically.
Database schema structure
Employees

Projects

id integer (primary key)
name varchar(100)
email varchar(100)
designation varchar(100)
doj date

id integer (primary key)
name varchar(100)
location varchar(100)

EmpProjects
empid integer(FKey)
projectid integer(FKey)
primarykey(empid,projectid)
Database schema in slick
For employee table:
case class Emp(id: Int, name: String, email: String, designation: String, doj: Date)
object Employees extends Table[Emp]("emp") {
def id = column[Int]("id", O.PrimaryKey)
def name = column[String]("name", O.NotNull, O.DBType("VARCHAR(100)"))
def email = column[String]("email", O.NotNull, O.DBType("VARCHAR(100)"))
def designation = column[String]("designation", O.NotNull, O DBType ("VARCHAR(100)"))
def doj = column[Date]("doj", O.NotNull)
def * = id ~ name ~ email ~ designation ~ doj <> (Emp.apply _, Emp unapply _)
}
Database schema in slick
For project table:

case class Project(id: Int, name: String, location: String)
object Projects extends Table[Project]("project") {
def id = column[Int]("id", O.PrimaryKey, O.DBType("INT"))
def name = column[String]("name", O.DBType("VARCHAR(100)"))
def location = column[String]("location", O.DBType("VARCHAR(100)"))
def * = id ~ name ~ location <> (Project, Project unapply _)
}
Database schema in slick
●

For empprojects table:
case class EmpProject(empId: Int, projectId: Int)
object EmpProjects extends Table[EmpProject]("emp_project") {
def empId = column[Int]("empid", O.DBType("INT"))
def projectId = column[Int]("projectid", O.DBType("INT"))
def * = empId ~ projectId <> (EmpProject , EmpProject unapply _)
def empFKey = foreignKey("emp_id_fkey", empId, Employees) { employees => employees.id }
def projectFKey = foreignKey("project_id_fkey", projectId, Projects) { projects => projects.id }
def empProjectPKey = primaryKey("emp_project_pkey", (empId, projectId))
}
Supported datatype
●

Numeric types: Byte, Short, Int, Long, BigDecimal, Float, Double

●

LOB types: java.sql.Blob, java.sql.Clob, Array[Byte]

●

Date types: java.sql.Date, java.sql.Time, java.sql.Timestamp

●

Boolean

●

String

●

Unit

●

java.util.UUID

If you need a custom column type you can implement TypeMapper and TypeMapperDelegate. The most
common scenario is mapping an application-specific type to an already supported type in the database.
This can be done much simpler by using a MappedTypeMapper which takes care of all the boilerplate:
def arrayTypeMapped = MappedTypeMapper.base[Array[Int], String](
array => array mkString ",",
str => { if (str != "") { (str split "," map Integer.parseInt) } else { Array() } })
Queries
●

Data Definition Language
-create/drop

●

Data manipulation language
- insert/update/delete
- Sorting and Filtering
- Joins
- Unions
Data Definition Language
Create tables:
dbObject withSession { implicit session: Session =>
val ddl= Employees.ddl ++ Projects.ddl ++ EmpProjects.ddl
ddl.create
}

Drop tables:
dbObject withSession { implicit session: Session =>
val ddl= Employees.ddl ++ Projects.ddl ++ EmpProjects.ddl
ddl.drop
}
Insert
●

Insert a row in Employees table:
Employees.insert( Emp(8, "satendra kumar", "satendra@knoldus.com", "consultant", java.sql.Date.valueOf("201306-3")) ) )

●

Insert List of rows in Employees table:
val listOfEmp = List(
Emp(1, "Janmejani", "Janmejani@knoldus.com", "consultant", java.sql.Date.valueOf("2012-11-26")),
Emp(2, "Anand", "anand@knoldus.com", "consultant", java.sql.Date.valueOf("2013-07-01")),
Emp(3, "Rishi Khandelwal ", "rishi@knoldus.com", "consultant", java.sql.Date.valueOf("2012-08-29"))
)
Employees.insertAll( listOfEmp: _*)
Retrieve row
●

Retrieve all rows:
Query(Employees).list
or
(for(emp <-Employees)yield(emp)).list

●

Retrieve all rows with only two columns(name and joning date):
( for(emp <-Employees) yield (emp.name, emp.doj) ).list
or
(Employees map {emp =>( emp.name,emp.doj)}).list
Update/Delete
●

Update name of employee (where employee id is 8):
val query = for (emp <- Employees if emp.id === 8) yield (emp.name)
query.update("satendra")

●

Delete employee (where employee id is 8 ):
val query = for (emp <- Employees if emp.id === 8) yield (emp)
query.delete

●

Delete all employee:
val query = for (emp <- Employees) yield (emp)
query.delete
Sorting and Filtering
●

Sort employee list by id:
(for (emp <- Employees) yield (emp)).sortBy(emp => emp.id).list

reverse sorting
(for (emp <- Employees) yield (emp)).sortBy(emp => emp.id.desc).list

●

Sort employee list by joining date:
(for (emp <- Employees) yield (emp)).sortBy(emp => emp.id).list

●

Filter employees which have joining date between 2013-07-10 and 2012-11-2:
Employees.filter{emp => (emp.doj <= Date.valueOf("2013-07-10") &&
Date.valueOf("2012-11-26")) }.list

emp.doj >=
Joins
●

Employee with project name and project location:
(for {
emp <- Employees
empproject <- EmpProjects if emp.id === empproject.empId
project <- Projects if (empproject.projectId === project.id)
} yield (emp.name, project.name,project.location)).list
Union
val query1 = Employees.filter { emp => emp.id === 8 }
val query2 = Employees.filter { emp => emp.id ===2}
(query1 union query2).list
Thanks

Mais conteúdo relacionado

Mais procurados

Map-Reduce and Apache Hadoop
Map-Reduce and Apache HadoopMap-Reduce and Apache Hadoop
Map-Reduce and Apache HadoopSvetlin Nakov
 
Cloudera Impala, updated for v1.0
Cloudera Impala, updated for v1.0Cloudera Impala, updated for v1.0
Cloudera Impala, updated for v1.0Scott Leberknight
 
Squeak DBX
Squeak DBXSqueak DBX
Squeak DBXESUG
 
ScalikeJDBC Tutorial for Beginners
ScalikeJDBC Tutorial for BeginnersScalikeJDBC Tutorial for Beginners
ScalikeJDBC Tutorial for BeginnersKazuhiro Sera
 
Ajax tutorial
Ajax tutorialAjax tutorial
Ajax tutorialKat Roque
 
Brief introduction of Slick
Brief introduction of SlickBrief introduction of Slick
Brief introduction of SlickKnoldus Inc.
 
Jdbc presentation
Jdbc presentationJdbc presentation
Jdbc presentationnrjoshiee
 
Omnisearch in AEM 6.2 - Search All the Things
Omnisearch in AEM 6.2 - Search All the ThingsOmnisearch in AEM 6.2 - Search All the Things
Omnisearch in AEM 6.2 - Search All the ThingsJustin Edelson
 
How and Where in GLORP
How and Where in GLORPHow and Where in GLORP
How and Where in GLORPESUG
 
Pavel kravchenko obj c runtime
Pavel kravchenko obj c runtimePavel kravchenko obj c runtime
Pavel kravchenko obj c runtimeDneprCiklumEvents
 
NyaruDBにゃるものを使ってみた話 (+Realm比較)
NyaruDBにゃるものを使ってみた話 (+Realm比較)NyaruDBにゃるものを使ってみた話 (+Realm比較)
NyaruDBにゃるものを使ってみた話 (+Realm比較)Masaki Oshikawa
 
JavaScript - Chapter 8 - Objects
 JavaScript - Chapter 8 - Objects JavaScript - Chapter 8 - Objects
JavaScript - Chapter 8 - ObjectsWebStackAcademy
 
Java7 New Features and Code Examples
Java7 New Features and Code ExamplesJava7 New Features and Code Examples
Java7 New Features and Code ExamplesNaresh Chintalcheru
 
JS Fest 2019/Autumn. Maciej Treder. Angular Schematics - Develop for developers
JS Fest 2019/Autumn. Maciej Treder. Angular Schematics - Develop for developersJS Fest 2019/Autumn. Maciej Treder. Angular Schematics - Develop for developers
JS Fest 2019/Autumn. Maciej Treder. Angular Schematics - Develop for developersJSFestUA
 
javascript objects
javascript objectsjavascript objects
javascript objectsVijay Kalyan
 
Building data flows with Celery and SQLAlchemy
Building data flows with Celery and SQLAlchemyBuilding data flows with Celery and SQLAlchemy
Building data flows with Celery and SQLAlchemyRoger Barnes
 
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)lennartkats
 

Mais procurados (20)

Map-Reduce and Apache Hadoop
Map-Reduce and Apache HadoopMap-Reduce and Apache Hadoop
Map-Reduce and Apache Hadoop
 
Cloudera Impala, updated for v1.0
Cloudera Impala, updated for v1.0Cloudera Impala, updated for v1.0
Cloudera Impala, updated for v1.0
 
Linq
LinqLinq
Linq
 
Squeak DBX
Squeak DBXSqueak DBX
Squeak DBX
 
ScalikeJDBC Tutorial for Beginners
ScalikeJDBC Tutorial for BeginnersScalikeJDBC Tutorial for Beginners
ScalikeJDBC Tutorial for Beginners
 
Ajax tutorial
Ajax tutorialAjax tutorial
Ajax tutorial
 
Brief introduction of Slick
Brief introduction of SlickBrief introduction of Slick
Brief introduction of Slick
 
Xml parsers
Xml parsersXml parsers
Xml parsers
 
Jdbc presentation
Jdbc presentationJdbc presentation
Jdbc presentation
 
Omnisearch in AEM 6.2 - Search All the Things
Omnisearch in AEM 6.2 - Search All the ThingsOmnisearch in AEM 6.2 - Search All the Things
Omnisearch in AEM 6.2 - Search All the Things
 
How and Where in GLORP
How and Where in GLORPHow and Where in GLORP
How and Where in GLORP
 
Pavel kravchenko obj c runtime
Pavel kravchenko obj c runtimePavel kravchenko obj c runtime
Pavel kravchenko obj c runtime
 
Lobos Introduction
Lobos IntroductionLobos Introduction
Lobos Introduction
 
NyaruDBにゃるものを使ってみた話 (+Realm比較)
NyaruDBにゃるものを使ってみた話 (+Realm比較)NyaruDBにゃるものを使ってみた話 (+Realm比較)
NyaruDBにゃるものを使ってみた話 (+Realm比較)
 
JavaScript - Chapter 8 - Objects
 JavaScript - Chapter 8 - Objects JavaScript - Chapter 8 - Objects
JavaScript - Chapter 8 - Objects
 
Java7 New Features and Code Examples
Java7 New Features and Code ExamplesJava7 New Features and Code Examples
Java7 New Features and Code Examples
 
JS Fest 2019/Autumn. Maciej Treder. Angular Schematics - Develop for developers
JS Fest 2019/Autumn. Maciej Treder. Angular Schematics - Develop for developersJS Fest 2019/Autumn. Maciej Treder. Angular Schematics - Develop for developers
JS Fest 2019/Autumn. Maciej Treder. Angular Schematics - Develop for developers
 
javascript objects
javascript objectsjavascript objects
javascript objects
 
Building data flows with Celery and SQLAlchemy
Building data flows with Celery and SQLAlchemyBuilding data flows with Celery and SQLAlchemy
Building data flows with Celery and SQLAlchemy
 
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
 

Semelhante a Slickdemo

PofEAA and SQLAlchemy
PofEAA and SQLAlchemyPofEAA and SQLAlchemy
PofEAA and SQLAlchemyInada Naoki
 
Introducing Apache Spark's Data Frames and Dataset APIs workshop series
Introducing Apache Spark's Data Frames and Dataset APIs workshop seriesIntroducing Apache Spark's Data Frames and Dataset APIs workshop series
Introducing Apache Spark's Data Frames and Dataset APIs workshop seriesHolden Karau
 
Intro to Spark and Spark SQL
Intro to Spark and Spark SQLIntro to Spark and Spark SQL
Intro to Spark and Spark SQLjeykottalam
 
Jdbc Java Programming
Jdbc Java ProgrammingJdbc Java Programming
Jdbc Java Programmingchhaichivon
 
SE2016 BigData Vitalii Bondarenko "HD insight spark. Advanced in-memory Big D...
SE2016 BigData Vitalii Bondarenko "HD insight spark. Advanced in-memory Big D...SE2016 BigData Vitalii Bondarenko "HD insight spark. Advanced in-memory Big D...
SE2016 BigData Vitalii Bondarenko "HD insight spark. Advanced in-memory Big D...Inhacking
 
Vitalii Bondarenko HDinsight: spark. advanced in memory big-data analytics wi...
Vitalii Bondarenko HDinsight: spark. advanced in memory big-data analytics wi...Vitalii Bondarenko HDinsight: spark. advanced in memory big-data analytics wi...
Vitalii Bondarenko HDinsight: spark. advanced in memory big-data analytics wi...Аліна Шепшелей
 
Database Programming Techniques
Database Programming TechniquesDatabase Programming Techniques
Database Programming TechniquesRaji Ghawi
 
Real-Time Spark: From Interactive Queries to Streaming
Real-Time Spark: From Interactive Queries to StreamingReal-Time Spark: From Interactive Queries to Streaming
Real-Time Spark: From Interactive Queries to StreamingDatabricks
 
Apache Spark, the Next Generation Cluster Computing
Apache Spark, the Next Generation Cluster ComputingApache Spark, the Next Generation Cluster Computing
Apache Spark, the Next Generation Cluster ComputingGerger
 
Kerberizing Spark: Spark Summit East talk by Abel Rincon and Jorge Lopez-Malla
Kerberizing Spark: Spark Summit East talk by Abel Rincon and Jorge Lopez-MallaKerberizing Spark: Spark Summit East talk by Abel Rincon and Jorge Lopez-Malla
Kerberizing Spark: Spark Summit East talk by Abel Rincon and Jorge Lopez-MallaSpark Summit
 
Ruby on Rails Oracle adaptera izstrāde
Ruby on Rails Oracle adaptera izstrādeRuby on Rails Oracle adaptera izstrāde
Ruby on Rails Oracle adaptera izstrādeRaimonds Simanovskis
 
Fast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on OracleFast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on OracleRaimonds Simanovskis
 
U-SQL Killer Scenarios: Custom Processing, Big Cognition, Image and JSON Proc...
U-SQL Killer Scenarios: Custom Processing, Big Cognition, Image and JSON Proc...U-SQL Killer Scenarios: Custom Processing, Big Cognition, Image and JSON Proc...
U-SQL Killer Scenarios: Custom Processing, Big Cognition, Image and JSON Proc...Michael Rys
 
Protractor framework – how to make stable e2e tests for Angular applications
Protractor framework – how to make stable e2e tests for Angular applicationsProtractor framework – how to make stable e2e tests for Angular applications
Protractor framework – how to make stable e2e tests for Angular applicationsLudmila Nesvitiy
 
Spark SQL Deep Dive @ Melbourne Spark Meetup
Spark SQL Deep Dive @ Melbourne Spark MeetupSpark SQL Deep Dive @ Melbourne Spark Meetup
Spark SQL Deep Dive @ Melbourne Spark MeetupDatabricks
 
Jan Stępień - GraalVM: Fast, Polyglot, Native - Codemotion Berlin 2018
Jan Stępień - GraalVM: Fast, Polyglot, Native - Codemotion Berlin 2018Jan Stępień - GraalVM: Fast, Polyglot, Native - Codemotion Berlin 2018
Jan Stępień - GraalVM: Fast, Polyglot, Native - Codemotion Berlin 2018Codemotion
 
Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracleyazidds2
 
Building node.js applications with Database Jones
Building node.js applications with Database JonesBuilding node.js applications with Database Jones
Building node.js applications with Database JonesJohn David Duncan
 

Semelhante a Slickdemo (20)

PofEAA and SQLAlchemy
PofEAA and SQLAlchemyPofEAA and SQLAlchemy
PofEAA and SQLAlchemy
 
Introducing Apache Spark's Data Frames and Dataset APIs workshop series
Introducing Apache Spark's Data Frames and Dataset APIs workshop seriesIntroducing Apache Spark's Data Frames and Dataset APIs workshop series
Introducing Apache Spark's Data Frames and Dataset APIs workshop series
 
Intro to Spark and Spark SQL
Intro to Spark and Spark SQLIntro to Spark and Spark SQL
Intro to Spark and Spark SQL
 
Jdbc Java Programming
Jdbc Java ProgrammingJdbc Java Programming
Jdbc Java Programming
 
SE2016 BigData Vitalii Bondarenko "HD insight spark. Advanced in-memory Big D...
SE2016 BigData Vitalii Bondarenko "HD insight spark. Advanced in-memory Big D...SE2016 BigData Vitalii Bondarenko "HD insight spark. Advanced in-memory Big D...
SE2016 BigData Vitalii Bondarenko "HD insight spark. Advanced in-memory Big D...
 
Vitalii Bondarenko HDinsight: spark. advanced in memory big-data analytics wi...
Vitalii Bondarenko HDinsight: spark. advanced in memory big-data analytics wi...Vitalii Bondarenko HDinsight: spark. advanced in memory big-data analytics wi...
Vitalii Bondarenko HDinsight: spark. advanced in memory big-data analytics wi...
 
Database Programming Techniques
Database Programming TechniquesDatabase Programming Techniques
Database Programming Techniques
 
Real-Time Spark: From Interactive Queries to Streaming
Real-Time Spark: From Interactive Queries to StreamingReal-Time Spark: From Interactive Queries to Streaming
Real-Time Spark: From Interactive Queries to Streaming
 
Apache Spark Workshop
Apache Spark WorkshopApache Spark Workshop
Apache Spark Workshop
 
Apache Spark, the Next Generation Cluster Computing
Apache Spark, the Next Generation Cluster ComputingApache Spark, the Next Generation Cluster Computing
Apache Spark, the Next Generation Cluster Computing
 
Kerberizing Spark: Spark Summit East talk by Abel Rincon and Jorge Lopez-Malla
Kerberizing Spark: Spark Summit East talk by Abel Rincon and Jorge Lopez-MallaKerberizing Spark: Spark Summit East talk by Abel Rincon and Jorge Lopez-Malla
Kerberizing Spark: Spark Summit East talk by Abel Rincon and Jorge Lopez-Malla
 
Ruby on Rails Oracle adaptera izstrāde
Ruby on Rails Oracle adaptera izstrādeRuby on Rails Oracle adaptera izstrāde
Ruby on Rails Oracle adaptera izstrāde
 
Fast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on OracleFast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on Oracle
 
U-SQL Killer Scenarios: Custom Processing, Big Cognition, Image and JSON Proc...
U-SQL Killer Scenarios: Custom Processing, Big Cognition, Image and JSON Proc...U-SQL Killer Scenarios: Custom Processing, Big Cognition, Image and JSON Proc...
U-SQL Killer Scenarios: Custom Processing, Big Cognition, Image and JSON Proc...
 
Protractor framework – how to make stable e2e tests for Angular applications
Protractor framework – how to make stable e2e tests for Angular applicationsProtractor framework – how to make stable e2e tests for Angular applications
Protractor framework – how to make stable e2e tests for Angular applications
 
Jdbc
JdbcJdbc
Jdbc
 
Spark SQL Deep Dive @ Melbourne Spark Meetup
Spark SQL Deep Dive @ Melbourne Spark MeetupSpark SQL Deep Dive @ Melbourne Spark Meetup
Spark SQL Deep Dive @ Melbourne Spark Meetup
 
Jan Stępień - GraalVM: Fast, Polyglot, Native - Codemotion Berlin 2018
Jan Stępień - GraalVM: Fast, Polyglot, Native - Codemotion Berlin 2018Jan Stępień - GraalVM: Fast, Polyglot, Native - Codemotion Berlin 2018
Jan Stępień - GraalVM: Fast, Polyglot, Native - Codemotion Berlin 2018
 
Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracle
 
Building node.js applications with Database Jones
Building node.js applications with Database JonesBuilding node.js applications with Database Jones
Building node.js applications with Database Jones
 

Mais de Knoldus Inc.

Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingMastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingKnoldus Inc.
 
Akka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionAkka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionKnoldus Inc.
 
Entity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxEntity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxKnoldus Inc.
 
Introduction to Redis and its features.pptx
Introduction to Redis and its features.pptxIntroduction to Redis and its features.pptx
Introduction to Redis and its features.pptxKnoldus Inc.
 
GraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfGraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfKnoldus Inc.
 
NuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxNuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxKnoldus Inc.
 
Data Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingData Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingKnoldus Inc.
 
K8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesK8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesKnoldus Inc.
 
Introduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxIntroduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxKnoldus Inc.
 
Robusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxRobusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxKnoldus Inc.
 
Optimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxOptimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxKnoldus Inc.
 
Azure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxAzure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxKnoldus Inc.
 
CQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxCQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxKnoldus Inc.
 
ETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationKnoldus Inc.
 
Scripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationScripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationKnoldus Inc.
 
Getting started with dotnet core Web APIs
Getting started with dotnet core Web APIsGetting started with dotnet core Web APIs
Getting started with dotnet core Web APIsKnoldus Inc.
 
Introduction To Rust part II Presentation
Introduction To Rust part II PresentationIntroduction To Rust part II Presentation
Introduction To Rust part II PresentationKnoldus Inc.
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Configuring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAConfiguring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAKnoldus Inc.
 
Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)Knoldus Inc.
 

Mais de Knoldus Inc. (20)

Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingMastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
 
Akka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionAkka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On Introduction
 
Entity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxEntity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptx
 
Introduction to Redis and its features.pptx
Introduction to Redis and its features.pptxIntroduction to Redis and its features.pptx
Introduction to Redis and its features.pptx
 
GraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfGraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdf
 
NuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxNuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptx
 
Data Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingData Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable Testing
 
K8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesK8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose Kubernetes
 
Introduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxIntroduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptx
 
Robusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxRobusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptx
 
Optimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxOptimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptx
 
Azure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxAzure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptx
 
CQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxCQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptx
 
ETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake Presentation
 
Scripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationScripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics Presentation
 
Getting started with dotnet core Web APIs
Getting started with dotnet core Web APIsGetting started with dotnet core Web APIs
Getting started with dotnet core Web APIs
 
Introduction To Rust part II Presentation
Introduction To Rust part II PresentationIntroduction To Rust part II Presentation
Introduction To Rust part II Presentation
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Configuring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAConfiguring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRA
 
Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)
 

Último

Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 

Último (20)

Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 

Slickdemo

  • 1. Scala Language Integrated Connection Kit(1.0.1) Satendra Kumar Software Consultant Knoldus Software LLP
  • 2. Topics Covered What is Slick Slick Key Features Quick Overview Live Demo
  • 3. What is Slick for{e ← Employees} yield e “select * from employee” ● Slick is a library written in scala for taking to database from scala programs. ● It is currently based on Jdbc. ● It is Successor of ScalaQuery. ● Developed By Typesafe and EPFL(École Polytechnique Fédérale de Lausanne)
  • 4. Slick's API ● Lifted embedding - The lifted embedding is Slick's stable query API which is based on ScalaQuery. ● Direct embedding - The direct embedding is a new experimental API for Slick that uses macros to allow expressions operating on standard Scala types to be used for database queries ● Plain SQL - Slick also allows you to write your own SQL queries and execute them with an API which is optimized for Scala, much easier to use and more concise than JDBC.
  • 5. Supported Databases ● PostgreSQL ● MySQL ● H2 ● Hsqldb ● Derby/JavaDB ● SQL Server ● SQLite ● Access ● Oracle ● DB2 * All green color database driver are open source * All yellow color database driver are not open source.( commercially supported by Typesafe)
  • 7. Easy ● Access stored data just like Scala collections. - for{ e ← Emp if( p.age === 25 )} yield e ● Unified session management based on JDBC Connections -forURL(url: String, user: String = null, password: String = null, prop: Properties = null, driver: String = null): Database - database.withSession{ // put code here } ● Supports SQL if you need it ● Simple setup
  • 8. Concise ● Slick uses scala syntax. ● Fetch results without pain - [jdbc] val sql = "select * from employee where name = ?“ val st = conn.prepareStatement( sql ) try { st.setString(1, name) val rs = st.executeQuery() val b = new ListBuffer[(Int, String)] while(rs.next) b.append((rs.getInt(1), rs.getString(2))) b.toList } finally st.close() - [slick]( for( e <- Epmloyees if e.name === name ) yield e).list
  • 9. Safe ● No SQL-injections ● Compile-time safety (types, names, no typos, etc.) -[jdbc] "select * from employee wehres nami = ' " + name + " ' " -[slick]for( e <- Employees if e.name === name ) yield e ● Type-safe use of stored procedures val getfeedbackByQuestionId = SimpleFunction.unary[ Int,String] ("getfeedbackbyquestionid")
  • 10. Composable Projects Employees * * EmpProjects ● def employeeByJoiningDate( from:Date, to:Date ) = Employees.filter( emp => emp.joiningDate >= from && emp.joiningDate <= to ) // projects with employee name (joining between 1-1-2013 and 1-10-2013) for{ emp <- employeeByJoiningDate(1-1-2013, 1-10-2013) empproject <- EmpProjects if (emp.id === empproject.empId) project <- Projects if (empproject.projectId === project.id) } yield (emp.name, project.name, project.location)
  • 11. Explicit ● No lazy loading means predictable performance. ● Only read the data you need. ● State less - no caches
  • 12. Overview Accessing databases using Slick’s lifted embedding requires the following steps: 1. Add the dependencies 2. Pick a driver for a particular database 3. Database Connection - Database object - Session 5. Describe Database schema 6. Write queries * In this presentation we are using postgres database.
  • 13. Dependencies Add dependencies in your build.sbt libraryDependencies ++= List( "com.typesafe.slick" %% "slick" % "1.0.1", "org.slf4j" % "slf4j-nop" % "1.6.4", "postgresql" % "postgresql" % "9.1-901.jdbc4" ) - Slick uses SLF4J for its own debug logging so you also need to add an SLF4J implementation. Here we are using slf4j-nop to disable logging. - You have to replace this with a real logging framework like Logback if you want to see log output
  • 14. Database drive Import database drive : // for postgres database ● import scala.slick.driver.PostgresDriver.simple._ - Since we are using postgres as our database system, we need to import features from Slick’s PostgresDriver. A driver’s simple object contains all commonly needed imports from the driver and other parts of Slick such as session handling.
  • 15. Database object Factory methods for creating Database objects: ● def forDataSource(ds: DataSource): Database - Create a Database based on a DataSource. ● def forName(name: String): Database - Create a Database based on the JNDI name of a DataSource. ● def forDriver(driver: Driver, url: String, user: String = null, password: String = null, prop: Properties = null): Database - Create a Database that directly uses a Driver to open new connections. This is needed to open a JDBC URL with a driver that was not loaded by the system ClassLoader. ● def forURL(url: String, user: String = null, password: String = null, prop: Properties = null, driver: String = null): Database - Create a Database that uses the DriverManager to open new connections.
  • 16. Session A database instance to which connections can be created. Encapsulates either a DataSource or parameters for DriverManager.getConnection(). Methods for session creation: def createSession(): Session - Create a new session. The session needs to be closed explicitly by calling its close() method. def withSession[T](f: (Session) ⇒ T): T - Run the supplied function with a new session and automatically close the session at the end. def withTransaction[T](f: (Session) ⇒ T): T - Run the supplied function with a new session in a transaction and automatically close the session at the end.
  • 17. Example Get database object: val dbObject = Database.forURL("jdbc:postgresql://localhost:5432/slickdemo", "sky", "satendra", null, "org.postgresql.Driver") Get Session: dbObject.withSession{ implicit session: Session => // write query here } * End of block session closed automatically.
  • 18. Database schema structure Employees Projects id integer (primary key) name varchar(100) email varchar(100) designation varchar(100) doj date id integer (primary key) name varchar(100) location varchar(100) EmpProjects empid integer(FKey) projectid integer(FKey) primarykey(empid,projectid)
  • 19. Database schema in slick For employee table: case class Emp(id: Int, name: String, email: String, designation: String, doj: Date) object Employees extends Table[Emp]("emp") { def id = column[Int]("id", O.PrimaryKey) def name = column[String]("name", O.NotNull, O.DBType("VARCHAR(100)")) def email = column[String]("email", O.NotNull, O.DBType("VARCHAR(100)")) def designation = column[String]("designation", O.NotNull, O DBType ("VARCHAR(100)")) def doj = column[Date]("doj", O.NotNull) def * = id ~ name ~ email ~ designation ~ doj <> (Emp.apply _, Emp unapply _) }
  • 20. Database schema in slick For project table: case class Project(id: Int, name: String, location: String) object Projects extends Table[Project]("project") { def id = column[Int]("id", O.PrimaryKey, O.DBType("INT")) def name = column[String]("name", O.DBType("VARCHAR(100)")) def location = column[String]("location", O.DBType("VARCHAR(100)")) def * = id ~ name ~ location <> (Project, Project unapply _) }
  • 21. Database schema in slick ● For empprojects table: case class EmpProject(empId: Int, projectId: Int) object EmpProjects extends Table[EmpProject]("emp_project") { def empId = column[Int]("empid", O.DBType("INT")) def projectId = column[Int]("projectid", O.DBType("INT")) def * = empId ~ projectId <> (EmpProject , EmpProject unapply _) def empFKey = foreignKey("emp_id_fkey", empId, Employees) { employees => employees.id } def projectFKey = foreignKey("project_id_fkey", projectId, Projects) { projects => projects.id } def empProjectPKey = primaryKey("emp_project_pkey", (empId, projectId)) }
  • 22. Supported datatype ● Numeric types: Byte, Short, Int, Long, BigDecimal, Float, Double ● LOB types: java.sql.Blob, java.sql.Clob, Array[Byte] ● Date types: java.sql.Date, java.sql.Time, java.sql.Timestamp ● Boolean ● String ● Unit ● java.util.UUID If you need a custom column type you can implement TypeMapper and TypeMapperDelegate. The most common scenario is mapping an application-specific type to an already supported type in the database. This can be done much simpler by using a MappedTypeMapper which takes care of all the boilerplate: def arrayTypeMapped = MappedTypeMapper.base[Array[Int], String]( array => array mkString ",", str => { if (str != "") { (str split "," map Integer.parseInt) } else { Array() } })
  • 23. Queries ● Data Definition Language -create/drop ● Data manipulation language - insert/update/delete - Sorting and Filtering - Joins - Unions
  • 24. Data Definition Language Create tables: dbObject withSession { implicit session: Session => val ddl= Employees.ddl ++ Projects.ddl ++ EmpProjects.ddl ddl.create } Drop tables: dbObject withSession { implicit session: Session => val ddl= Employees.ddl ++ Projects.ddl ++ EmpProjects.ddl ddl.drop }
  • 25. Insert ● Insert a row in Employees table: Employees.insert( Emp(8, "satendra kumar", "satendra@knoldus.com", "consultant", java.sql.Date.valueOf("201306-3")) ) ) ● Insert List of rows in Employees table: val listOfEmp = List( Emp(1, "Janmejani", "Janmejani@knoldus.com", "consultant", java.sql.Date.valueOf("2012-11-26")), Emp(2, "Anand", "anand@knoldus.com", "consultant", java.sql.Date.valueOf("2013-07-01")), Emp(3, "Rishi Khandelwal ", "rishi@knoldus.com", "consultant", java.sql.Date.valueOf("2012-08-29")) ) Employees.insertAll( listOfEmp: _*)
  • 26. Retrieve row ● Retrieve all rows: Query(Employees).list or (for(emp <-Employees)yield(emp)).list ● Retrieve all rows with only two columns(name and joning date): ( for(emp <-Employees) yield (emp.name, emp.doj) ).list or (Employees map {emp =>( emp.name,emp.doj)}).list
  • 27. Update/Delete ● Update name of employee (where employee id is 8): val query = for (emp <- Employees if emp.id === 8) yield (emp.name) query.update("satendra") ● Delete employee (where employee id is 8 ): val query = for (emp <- Employees if emp.id === 8) yield (emp) query.delete ● Delete all employee: val query = for (emp <- Employees) yield (emp) query.delete
  • 28. Sorting and Filtering ● Sort employee list by id: (for (emp <- Employees) yield (emp)).sortBy(emp => emp.id).list reverse sorting (for (emp <- Employees) yield (emp)).sortBy(emp => emp.id.desc).list ● Sort employee list by joining date: (for (emp <- Employees) yield (emp)).sortBy(emp => emp.id).list ● Filter employees which have joining date between 2013-07-10 and 2012-11-2: Employees.filter{emp => (emp.doj <= Date.valueOf("2013-07-10") && Date.valueOf("2012-11-26")) }.list emp.doj >=
  • 29. Joins ● Employee with project name and project location: (for { emp <- Employees empproject <- EmpProjects if emp.id === empproject.empId project <- Projects if (empproject.projectId === project.id) } yield (emp.name, project.name,project.location)).list
  • 30. Union val query1 = Employees.filter { emp => emp.id === 8 } val query2 = Employees.filter { emp => emp.id ===2} (query1 union query2).list