Created
September 25, 2013 09:20
-
-
Save potato2003/6697131 to your computer and use it in GitHub Desktop.
StackableController + Slick + PlayFramework で暗黙的にDBSession使いまわすのやつメモ
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 SlickDBSessionElement extends StackableController { | |
self: Controller => | |
import play.api.db.slick | |
type Session = slick.Session | |
case object DBSessionKey extends RequestAttributeKey[Session] | |
override def proceed[A](req: RequestWithAttributes[A])(f: RequestWithAttributes[A] => Result): Result = { | |
val session:Session = play.api.db.slick.DB.createSession() | |
super.proceed(req.set(DBSessionKey, session))(f) | |
} | |
override def cleanupOnSucceeded[A](req: RequestWithAttributes[A]): Unit = { | |
try { | |
req.get(DBSessionKey).map(_.close()) | |
} finally { | |
super.cleanupOnSucceeded(req) | |
} | |
} | |
override def cleanupOnFailed[A](req: RequestWithAttributes[A], e: Exception): Unit = { | |
try { | |
req.get(DBSessionKey).map(_.close()) | |
} finally { | |
super.cleanupOnFailed(req, e) | |
} | |
} | |
implicit def dbSession(implicit req: RequestWithAttributes[_]): Session = req.get(DBSessionKey).get | |
def withTransaction[T](f: => T)(implicit req: RequestWithAttributes[_]): T = { | |
slick.DB("master").withTransaction(f) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment