我正在尝试学习如何使用Play和Squeryl制作一个简单的数据库应用程序。我已经按照Play教程中的任务应用程序完成了任务,但我想改变模型/架构,以便使用Squeryl而不是Anorm。我一直在查看不同的tutorials,示例和answers,但我还没有真正弄清楚如何做到这一点。
因此,鉴于Play教程(ScalaTodoList)的源代码,我该如何继续使用Squeryl使其工作?
更具体地说:
在
其余文件保持与Play教程结束时一样。
因此,鉴于Play教程(ScalaTodoList)的源代码,我该如何继续使用Squeryl使其工作?
更具体地说:
- 如何在我的模型中实现
all()
、create()
和delete()
方法?(我想使用自增长的ID来为任务分配ID) - 目前在
Build.scala
和Global.scala
中硬编码了要使用哪个数据库适配器(详见下文)。我该如何让它自动在开发/测试环境下使用H2,在Heroku上使用Postgres,就像在Play教程中对Anorm一样? - 如何确保它自动创建我的表格?
这是我迄今为止所做的
我完成了Play ScalaTodoList教程。
在project/Build.scala
中的object ApplicationBuild
,我添加了以下依赖项:
// From the "Squeryl Getting Started tutorial"
val posgresDriver = "postgresql" % "postgresql" % "8.4-702.jdbc4"
val h2 = "com.h2database" % "h2" % "1.2.127"
// From the "Squeryl Getting Started tutorial"
libraryDependencies ++= Seq(
"org.squeryl" %% "squeryl" % "0.9.5",
h2
)
// From the Play tutorial
val appDependencies = Seq(
// Add your project dependencies here,
"org.squeryl" %% "squeryl" % "0.9.5", // Copied from above so that it compiles (?)
"postgresql" % "postgresql" % "8.4-702.jdbc4"
)
添加了 app/Global.scala
文件(从上面提到的 SO answer 中获取,只是将适配器更改为 H2):
import play.db.DB
import play.api.Application
import play.api.GlobalSettings
import org.squeryl._
import org.squeryl.adapters._
object Global extends GlobalSettings {
override def onStart(app: Application): Unit =
{
SessionFactory.concreteFactory = Some(
() => Session.create(DB.getDataSource().getConnection(),
dbAdapter));
}
override def onStop(app: Application): Unit =
{
}
val dbAdapter = new H2Adapter(); // Hard coded. Not good.
}
在
app/models/Task.scala
中,我添加了导入并删除了all()
、create()
和delete()
中的Anorm实现。 Play教程中的控制器希望all()
方法返回List[Task]
。import org.squeryl.PrimitiveTypeMode._
import org.squeryl.Schema
import org.squeryl.annotations.Column
case class Task(id: Long, label: String)
object Task extends Schema {
val tasks = table[Task] // Inspired by Squeryl tutorial
def all(): List[Task] = {
List[Task]() // ??
}
def create(label: String) {
// ??
}
def delete(id: Long) {
// ??
}
}
其余文件保持与Play教程结束时一样。