1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

slickでのPlainSQLからケースクラスへのマッピングメモ

Posted at

テーブル定義

CREATE TABLE table1(
  table1_primary,
  table1_name,
  table2_primary,
  PRIMARY KEY(table1_primary)
);
CREATE TABLE table2(
  table2_primary,
  table2_name,
  PRIMARY KEY(table2_primary)
);

entity

entities.scala
package com.exsample.models

import slick.jdbc.GetResult

package entities {

  case class Table2(
    table2Primary: Int,
    table2Name: String
  )
  object Table2 {
    implicit val table2Result = GetResult(r =>
      r.<<,
      r.<<
    )
  }

  case class Table1(
    table1Primary: Int,
    table1Name: String,
    table2: Table2
  )
  object Table1 {
    implicit val table1Result = GetResult(r =>
      r.<<,
      r.<<,
      r.<<[Table2]
    )
  }
}

Repository

SlickRepository.scala
package com.exsample.repositories

import scala.concurrent.Future
import slick.driver.MySQLDriver.api._
import slick.jdbc.JdbcBackend.Database
import slick.jdbc.GetResult
import com.exsample.entities.Table1

trait SlickRepository {

  def selectAll(): Future[Vector[Table1]]
}

class SlickRepositoryImpl(db: Database) extends SlickRepository {

  override def selectAll() = db.run(Sqls.selectAll())
}

object Sqls {

  def selectAll() =
    sql"""
      SELECT
        t1.table1_primary,
        t1.table1_name,
        t2.table2_primary,
        t2.table2_name
      FROM
        table1 t1
      JOIN
        table2 t2
      ON
        t2.table2_primary = t1.table2_primary
    """.as[Table1]
}

詳しくは↓

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?