Last active
August 29, 2015 14:16
-
-
Save j5ik2o/973fe2fde3ba8f141bb1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
trait Entity[ID] { | |
val id: ID | |
// equals, hashCodeはコレクションに入れた時に検索しやすくするために定義している | |
override def equals(obj: Any): Boolean = obj match { | |
case that: Entity[_] => id == that.id | |
case _ => false | |
} | |
override def hashCode: Int = 31 * id.hasCode | |
} | |
trait EntityIOContext | |
trait Repository[ID, E <: Enttity[ID]] { | |
type Ctx = EntityIOContext | |
def findById(id: ID)(ctx: Ctx): Try[E] | |
def store(entity: E)ctx: Ctx): Try[E] | |
} | |
case class EntityIOContextOnJDBC(sesion: DBSession) extends EntityIOContext | |
abstract class AbstractRepositoryOnJDBC[ID, E <: Entity[ID] extends Repository[ID, E] { | |
protected def convertToEntity(resultSet: WrappedResultSet): E | |
protected def convertToMap(entity: Entity): Map[String, Any] | |
private val userDao = new UserDao | |
private def getSession(ctx: Ctx) = ctx match { | |
case EntityIOContextOnJDBC(session) => session | |
case _ => throw new Exception(...) | |
} | |
override def findById(id: Long)(implicit ctx: Ctx) = { | |
implicit val session = getSession(ctx) | |
userDao.selectById(id).map(convertToEntity) | |
} | |
override def store(entity: E)(implicit ctx: Ctx) = { | |
implicit val session = getSession(ctx) | |
userDao.insertOrUpdate(convertToMap(entity)) | |
} | |
} | |
abstract class AbstractRepositoryOnMemory[ID, E <: Entity[ID](entities: mutable.Map[ID, E] ) extends Repository[ID, E] { | |
override def findById(id: Long)(ctx: Ctx) = Try { | |
entities(id).getOrElse(throw EntityNotFoundException) | |
} | |
override def store(entity: E)(implicit ctx: Ctx) = { | |
entities.put(id, entity) | |
Success(entity) | |
} | |
} | |
case class Employee(id: Long, name: String) extends Entity[Long] | |
case class EmployeeRepositoryOnJDBC | |
extends AbstractRepositoryOnJDBC[Long, Employee] | |
case class EmployeeRepositoryOnMemory(entities: mutable.Map[Long, Employee] = mutable.Map.empty) | |
extends AbstractRepositoryOnMemory[Long, Employee](entities) | |
object Main extends App { | |
implicit val ctx = EntityIOContextOnJDBC(AutoSession) | |
val repository = new EmployeeRepositoryOnJDBC() | |
val entity = Employee(1, "Junichi Kato") | |
repository.store(entity).foreach { _ => | |
repository.findById(entity.id).foreach(println) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment