Scala, slick, mysql technologies

How to update entire database record using Slick

Slick documentation says how to perform update operation for specific column, but doesn't contain any examples of updating entire record.

Below is tiny example of how to do that.

Let's assume we have a mapped table that uses a custom type Customer:

1
2
3
4
5
6
7
8
9
10
import scala.slick.driver.MySQLDriver.simple._

case class Customer(id: Option[Long], firstName: String, lastName: String)

object Customers extends Table[Customer]("customers") {
  def id = column[Long]("id", O.PrimaryKey, O.AutoInc)
  def firstName = column[String]("first_name")
  def lastName = column[String]("last_name")
  def * = id.? ~ firstName ~ lastName <> (Customer, Customer.unapply _)
}

The simplest way to update the whole Customer record is calling where method on Table object and then executing update with Customer object as an argument. For example,

1
2
3
4
5
  ...
  val updatedCustomer = Customer(Some(1L), "First", "Last")
  ...
  Customers.where(_.id === updatedCustomer.id.get).update(updatedCustomer)
  ...

Hope you find it helpful,

Looking to hire a software engineer?
Don't hesitate to contact us.

Comments