Scala Slick: Functional Relational Mapping for Scala
Take your programming skills to the next level with interactive lessons and real-world projects.
Explore Coddy →Scala Slick is a modern database query and access library for Scala. It allows you to work with relational databases using Scala code, providing a type-safe and composable API for database operations.
Key Features of Slick
- Type-safe queries
- Composable query abstractions
- Support for multiple database systems
- Asynchronous execution
- Functional programming approach
Getting Started with Slick
To use Slick in your Scala project, you need to add the following dependency to your SBT build file:
libraryDependencies += "com.typesafe.slick" %% "slick" % "3.3.3"
Defining Table Schemas
In Slick, you define your database schema using Scala case classes and Table objects. Here's an example:
import slick.jdbc.H2Profile.api._
case class User(id: Int, name: String, email: String)
class Users(tag: Tag) extends Table[User](tag, "USERS") {
def id = column[Int]("ID", O.PrimaryKey, O.AutoInc)
def name = column[String]("NAME")
def email = column[String]("EMAIL")
def * = (id, name, email) <> (User.tupled, User.unapply)
}
val users = TableQuery[Users]
Querying the Database
Slick provides a powerful DSL for querying the database. Here's an example of a simple query:
val query = users.filter(_.name like "%John%")
val result: Future[Seq[User]] = db.run(query.result)
Inserting Data
Inserting data into the database is straightforward with Slick:
val insertAction = users += User(0, "Alice", "alice@example.com")
val insertResult: Future[Int] = db.run(insertAction)
Best Practices
- Use Futures for asynchronous operations
- Leverage type inference for cleaner code
- Utilize case classes for domain models
- Implement proper error handling using Try or Either
Advanced Features
Slick offers advanced features like:
- Compiled queries for better performance
- Custom column mappings
- Plain SQL support for complex queries
- Integration with Play Framework
By mastering Scala Slick, you can efficiently work with databases in your Scala applications, leveraging the power of functional programming and type safety.