光滑的入门代码
在 build.sbt
中,请确保包含(此处为 Mysql 和 PostGreSQL):
"mysql" % "mysql-connector-java" % "5.1.20",
"org.postgresql" % "postgresql" % "9.3-1100-jdbc4",
"com.typesafe.slick" %% "slick" % "3.1.1",
"com.typesafe.play" %% "play-slick" % "1.1.1"
在你的 application.conf
中,添加:
mydb.driverjava="slick.driver.MySQLDriver$"
mydb.driver="com.mysql.jdbc.Driver"
mydb.url="jdbc:mysql://hostaddress:3306/dbname?zeroDateTimeBehavior=convertToNull"
mydb.user="username"
mydb.password="password"
要使 RDBMS 独立架构创建如下所示的对象
package mypackage
import slick.driver.MySQLDriver
import slick.driver.PostgresDriver
object SlickDBDriver{
val env = "something here"
val driver = env match{
case "postGreCondition" => PostgresDriver
case _ => MySQLDriver
}
}
在创建新模型时:
import mypackage.SlickDBDriver.driver.api._
import slick.lifted.{TableQuery, Tag}
import slick.model.ForeignKeyAction
case class MyModel(
id: Option[Long],
name: String
) extends Unique
class MyModelDB(tag: Tag) extends IndexedTable[MyModel](tag, "my_table"){
def id = column[Long]("id", O.PrimaryKey, O.AutoInc)
def name = column[String]("name")
def * = (id.? , name) <> ((MyModel.apply _).tupled, MyModel.unapply _)
}
class MyModelCrud{
import play.api.Play.current
val dbConfig = DatabaseConfigProvider.get[JdbcProfile](Play.current)
val db = dbConfig.db
val query = TableQuery[MyModelDB]
// SELECT * FROM my_table;
def list = db.run{query.result}
}