我正在使用 Play 2.2 在 Scala 中创建一个应用程序。我使用 play-slick 0.5.0.8
作为我的 MySQL 数据库连接器。我有以下应用程序 Controller :
package controllers
import models._
import models.database._
import play.api._
import play.api.mvc._
import play.api.Play.current
import play.api.db.slick._
object Application extends Controller {
// WORKS:
def test = DBAction {
implicit session => Ok(views.html.test(Cameras.findById(1)))
}
// DOES NOT WORK:
def photo = Action {
val p = PhotoFetcher.fetchRandomDisplayPhoto(someParametersBlah))
Ok(views.html.photo(p))
}
}
如您所见,test
DBAction 工作正常,它能够很好地从数据库中获取照片。不幸的是,photo
操作不起作用。
我的 PhotoFetcher.fetchRandomDisplayPhoto(blah)
做了很多不同的事情。隐藏在其中的是对 Cameras.findById(blah)
的调用,它应该返回一个 Camera
对象(在 test
DBAction 中工作) .但是,使用此配置我收到以下错误:
could not find implicit value for parameter s: slick.driver.MySQLDriver.simple.Session
我试过将 photo
操作变成 DBAction,如下所示:
def photo = DBAction {
implicit session => {
val p = PhotoFetcher.fetchRandomDisplayPhoto(someParametersBlah))
Ok(views.html.photo(p))
}
}
但这只会导致相同的丢失 session 错误。这就像 PhotoFetcher 不知道隐式 session 。
我尝试过的另一件事是在我的 PhotoFetcher
中导入 slick.session.Database.threadLocalSession
,但这只会导致以下错误:
SQLException: No implicit session available; threadLocalSession can only be used within a withSession block
如果有任何帮助,这是我的 Cameras
对象的简化版本:
package models.database
import models.Format.Format
import scala.slick.driver.MySQLDriver.simple._
case class Camera(id: Long,
otherStuff: String)
trait CamerasComponent {
val Cameras: Cameras
class Cameras extends Table[Camera]("cameras") {
def id = column[Long]("id", O.PrimaryKey, O.AutoInc)
def otherStuff = column[String]("otherStuff", O.NotNull)
def * = id ~ otherStuff <> (Camera.apply _, Camera.unapply _)
val byId = createFinderBy(_.id)
val byOtherStuff = createFinderBy(_.otherStuff)
}
}
object Cameras extends DAO {
def insert(camera: Camera)(implicit s: Session) { Cameras.insert(camera) }
def findById(id: Long)(implicit s: Session): Option[Camera] = Cameras.byId(id).firstOption
def findByOtherStuff(otherStuff: String)(implicit s: Session): Option[Camera] = Cameras.byOtherStuff(model).firstOption
}
所以,好像我在某个地方被搞错了。现在,我只能直接从 Controller DBAction 访问我的 DAO 对象,而不是从某个不同类的内部访问。任何帮助,将不胜感激。谢谢!
最佳答案
PhotoFetcher.fetchRandomDisplayPhoto.fetchRandomDisplayPhoto
的定义是否采用隐式 session ?
// PhotoFetcher
def fetchRandomDisplayPhoto(args: Blah*)(implicit s: Session) = {
// ...
val maybeCam = Cameras.findById(blah) // <- sees the implicit session
// ...
}
或者您是否依赖 PhotoFetcher
中的 threadLocalsession
? (fetchRandomDisplayPhoto
没有隐式 session 参数)?
虽然 Slick 的 threadLocalSession 可以方便地快速尝试一些东西,但它可能会在以后导致困惑和不清晰。最好只对调用 Slick 模型的所有方法使用显式 (implicit s: Session)
参数列表。这也玩
DBAction
很好,让框架管理 session 。
缺点是你必须在所有方法上都有 (implicit s: Session)
- 那里
是这样的解决方法:
https://github.com/freekh/play-slick/issues/20
Scala 并不冗长而且非常适合重构 - 所以我建议考虑一下
关于当你来到它时穿过那座桥,并使用 DBAction
进行所有操作
做数据库的东西;给所有调用你的数据库模型的方法
隐式 session ,看看能给你带来多少里程。
关于mysql - Scala Play Framework Slick Session 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19488135/