4

I'm trying a simple test application with Slick and the Play2 Framework, but the compiler keeps complaining the implicit session cannot be inferred.

Here is my Build.scala:

import sbt._
import Keys._
import play.Project._

object ApplicationBuild extends Build {

  val appName         = "dummy"
  val appVersion      = "1.0"

  val appDependencies = Seq(
    jdbc,
    "mysql" % "mysql-connector-java" % "5.1.26",
    "com.typesafe.slick" %% "slick" % "1.0.1"
  )


  val main = play.Project(appName, appVersion, appDependencies).settings(
    // Add your own project settings here      
  )

}

And this is my Global singleton that holds my database connections:

package models

import play.api.Play.current
import play.api.db.DB
import slick.session.Session
import slick.driver.MySQLDriver.simple._
import scala.slick.session.Database.threadLocalSession


object Global {

  lazy val database = Database.forDataSource(DB.getDataSource())

  lazy val session = database.createSession()

}

And my controller:

package controllers

import scala.language.implicitConversions
import play.api._
import play.api.mvc._
import models.Global.session

import slick.driver.MySQLDriver.simple._

object Application extends Controller {

  def index = Action {
    /*slick.driver.MySQLDriver.simple.*/Query(Foo).foreach( _ => () ) // Do nothing for now
    Ok(views.html.index("hola"))
  }

  object Foo extends Table[(Long, String, String)]("Foo") {
    def * = column[Long]("id") ~ column[String]("bar1") ~ column[String]("bar2")
  }

}

As you can see my Global.session val is imported, but it keeps saying no implicit session was found.

4

1 回答 1

4

要进行查询,您需要两件事:连接到数据库和会话,所以您的问题是如何定义和使用它们。在Database.threadLocalSession范围内,您可以像这样进行查询:

Database.forURL("jdbc:h2:mem:play", driver = "org.h2.Driver") withSession {
          //create table
          Foo.ddl.create
          //insert data
          Foo.insert((1.toLong,"foo","bar"))
          //get data
          val data : (Long,String,String) = (for{f<-Foo}yield(f)).first
}

或者你可以这样做:

val database  = Database.forDataSource(DB.getDataSource())
 database.withSession{ implicit session : Session =>
          Foo.ddl.create
          Foo.insert((1.toLong,"foo","bar"))
          val data : (Long,String,String) = (for{f<-Foo}yield(f)).first
}

我创建了一个测试,它工作正常,你可以玩它:

"Foo should be creatable " in {
  running(FakeApplication(additionalConfiguration = inMemoryDatabase())) {
    val database  = Database.forDataSource(DB.getDataSource())
    database.withSession{ implicit session : Session =>
      Foo.ddl.create
      Foo.insert((1.toLong,"foo","bar"))
      val data : (Long,String,String) = (for{f<-Foo}yield(f)).first

      data._1 must equalTo(1)
    }
  }
}

你也可以看看这里

于 2013-09-18T10:39:15.710 回答