【发布时间】:2013-12-20 00:29:22
【问题描述】:
Emm...我正在用 Play 2 试用 Slick。表创建过程变得非常令人沮丧,因为与其他 ORM(如 ebean)不同,Slick 不会检测数据库是否已创建,如果已经存在表存在,会报异常。我只是不想每次重启服务器时都删除和创建,所以我决定写一个小函数来帮助我:
def databaseCreate(tables: Table*) = {
for (table <- tables) {
if (MTable.getTables(table.getClass.getName).list.isEmpty) table.ddl.create
}
}
它的作用是接收一些像这样的对象:
object Tag extends Table [(Option[Int], String)]("Tags") {
def id = column[Int]("TAG_ID", O.PrimaryKey, O.AutoInc)
def tag_name = column[String]("TAG_NAME")
def * = id.? ~ tag_name
}
并使用scala.slick.jdbc.meta.MTable 中的MTable 方法来了解该表是否存在。然后我遇到了一个简单的 Java 反射问题。如果databaseCreate 方法采用字符串,那么我可以调用.ddl.create。所以我决定传入对象并使用 relfection:table.getClass.getName。唯一的问题是类型不匹配:(来自我的 IDE)
预期:MySQLDriver.simple.type#Table,实际:BlogData.Tag.type
BlogData 是我用来存储所有较小表对象的大对象。我该如何解决这个不匹配问题?使用一大堆asInstanceOf?这会使命令变得难以忍受又长又丑……
更正:
类型不匹配是一个误报,它来自 IDE,而不是来自类型安全控制台编译器。真正的问题是:
type Table takes type parameters
def databaseCreate(tables: Table*) = {
^
one error found
然后我按照建议更改了代码:
def databaseCreate(tables: Table[_]*)(implicit session: Session) = {
for (table <- tables) {
if (MTable.getTables(table.tableName).list.isEmpty) table.ddl.create
}
}
然后我得到了这个错误:
ambiguous implicit values: both value session of type slick.driver.MySQLDriver.simple.Session and method threadLocalSession in object Database of type => scala.slick.session.Session match expected type scala.slick.session.Session
if (MTable.getTables(table.tableName).list.isEmpty) table.ddl.create
^
one error found
我的导入在这里:
import play.api.GlobalSettings
import play.api.Application
import models.BlogData._
import scala.slick.driver.MySQLDriver.simple._
import Database.threadLocalSession
import play.api.Play.current
import scala.slick.jdbc.meta.MTable
【问题讨论】:
标签: scala playframework slick