The examples in this chapter demonstrate how one might build a functional interface to access JDBC.
To run the examples for this chapter, you will need a MySQL database server running on port 3306.
## Model classes
Gender.scala
: a Scala enum to represent gender.Physicist.scala
: case class describing a physicist.
SqlUtils.scala
: Routines for opening a connection using the loan pattern and for wrapping aResultSet
instance in a Scala stream.RichConnection.scala
: class wrapping a JDBC connection to allow openingResultSet
instances using the loan pattern. This class should not be used explicitly. Instead, we provide implicit conversions from a JDBCConnection
instance to an instance ofRichConnection
using the pimp my library pattern. These implicit conversions are provided in theImplicits.scala
code file.
## Type classes
SqlReader.scala
: abstract trait and specific implementations of aSqlReader[T]
trait that exposes aread
method describing how to extract an instance of typeT
from a field in aResultSet
.RichResultSet.scala
: class wrapping a JDBCResultSet
instance to offer aread[T]
method that extracts an instance ofT
from aResultSet
. Theread[T]
method relies on the existence of aSqlReader[T]
type class. TheRichResultSet
class should not be used explicitly. Rather, we define a conversion inImplicits.scala
that implicitly adds the functionality in theRichResultSet
class to a JDBCResultSet
.Implicits.scala
: Implicit conversions from a JDBCConnection
to aRichConnection
and back, and from aResultSet
to aRichResultSet
.
## Data access object
Data access objects (DAOs) are objects that provide functions to serialize and deserialize specific classes to and from a SQL database. They assume the SQL table follows a specific schema.
PhysicistDao.scala
provides a method for reading every row in aphysicists
SQL table, converting each row to an instance of thePhysicist
case class.PhysicistDaoDemo.scala
exercises thePhysicistDao
class.