Introduction to Slick: Plain SQL Usage

Updated: Jun 17, 2018

In this post I will cover usage of the Slick library, which provides a Scala-centric API over JDBC. Slick offers 3 flavors for querying the DB; I will focus on the plain SQL flavor.

Note: Slick is only compatible with Scala 2.10.

Maven dependency:

DB table:

We will represent the Animal domain object using the following case class:

Note: The first parameter is complex type (UUID) and the third parameter is also complex type (Joda DateTime).

We will hide all DB operations using a DAO, as described by the following trait:

And the implementation:

  • The DAO is dependent on a javax.sql.DataSource.

  • In the second line, we created a Slick Database object using the provided DataSource.

  • allAnimals() uses the queryNA[Animal] function and returns a Seq of Animals.

  • animalById() uses the sql String interpolator. The .as[Animal] method tells the function to return an instance of Animal, and .firstOption() returns only the first result, wrapped in an Option.

  • deleteAnimalById() uses the sqlu String interpolator for update/insert. The result is always an Int representing the number of affected trows.

  • The implicit val getAnimalResult is very important. It tells Slick how to create the object, and it encapsulates the logic constructing the complex types mentioned earlier.

This post was written by Kfir Bloch.

You can also follow him on Twitter

#interpolation #Scala #slick #SQL #typesafe


Recent Posts

See All