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.
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"
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]
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 into the database is straightforward with Slick:
val insertAction = users += User(0, "Alice", "alice@example.com")
val insertResult: Future[Int] = db.run(insertAction)
Slick offers advanced features like:
By mastering Scala Slick, you can efficiently work with databases in your Scala applications, leveraging the power of functional programming and type safety.