Creating a data access layer

Let's bring together everything that we have seen and build a data-mapper class for fetching Physicist objects from the database. These classes (also called data access objects) are useful to decouple the internal representation of an object from its representation in the database.

We start by defining the Physicist class:

// Physicist.scala
case class Physicist(
  val name:String,
  val gender:Gender.Value
)

The data access object will expose a single method, readAll, that returns a Vector[Physicist] of all the physicists in our database:

// PhysicistDao.scala

import java.sql.{ ResultSet, Connection }
import Implicits._ // implicit conversions

object PhysicistDao {

  /* Helper method for reading a single row */
  private def readFromResultSet(results:ResultSet):Physicist = {
    Physicist(
      results.read[String]("name"),
      results.read[Gender.Value]("gender")
    )
  }

  /* Read the entire 'physicists' table. */
  def readAll(connection:Connection):Vector[Physicist] = {
    connection.withQuery("SELECT * FROM physicists") {
      results =>
        val resultStream = SqlUtils.stream(results)
        resultStream.map(readFromResultSet).toVector
    }
  }
}

The data access layer can be used by client code as in the following example:

object PhysicistDaoDemo extends App {

  val physicists = SqlUtils.usingConnection("test") {
    connection => PhysicistDao.readAll(connection)
  }

  // physicists is a Vector[Physicist] instance.
  physicists.foreach { println }
  //=> Physicist(Albert Einstein,Male)
  //=> Physicist(Marie Curie,Female)
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.202.27