我是Scala和Slick的新手。 尝试使用此处https://github.com/slick/slick-codegen-example的代码生成器示例并将其更改为Postgres驱动程序。 这是我在Build.Scala文件中的代码:
import sbt._
import Keys._
import Tests._
object myBuild extends Build {
val slickVersion = "3.0.2"
lazy val mainProject = Project(
id="main",
base=file("."),
settings = Project.defaultSettings ++ Seq(
scalaVersion := "2.11.6",
libraryDependencies ++= List(
"com.typesafe.slick" %% "slick" % slickVersion,
"com.typesafe.slick" %% "slick-codegen" % slickVersion,
"org.slf4j" % "slf4j-nop" % "1.7.12",
"org.postgresql" % "postgresql" % "9.4-1201-jdbc41"
),
slick <<= slickCodeGenTask, // register manual sbt command
sourceGenerators in Compile <+= slickCodeGenTask // register automatic code generation on every compile, remove for only manual use
)
)
// code generation task
lazy val slick = TaskKey[Seq[File]]("gen-tables")
lazy val slickCodeGenTask =
(sourceManaged, dependencyClasspath in Compile, runner in Compile, streams) map { (dir, cp, r, s) =>
val outputDir = (dir / "slick").getPath // place generated files in sbt's managed sources folder
val url = "jdbc:postgresql://localhost:5432/db'" // connection info
val jdbcDriver = "org.postgresql.Driver"
val slickDriver = "slick.driver.PostgresDriver"
val pkg = "dao"
val user="postgres"
val password="pass"
toError(r.run("slick.codegen.SourceCodeGenerator", cp.files, Array(slickDriver, jdbcDriver, url, outputDir, pkg, user, password), s.log))
val fname = outputDir + "/dao/Tables.scala"
Seq(file(fname))
}
}
我唯一改变的是驱动程序和登录名,密码。据我所知,它应该在每次运行时生成代码
激活器运行
但它不会生成任何代码。另外,如何手动运行?
答案 0 :(得分:3)
您可以将其添加到build.sbt文件中:
val conf = ConfigFactory.parseFile(new File("conf/application.conf")).resolve()
slick <<= slickCodeGenTask
lazy val slick = TaskKey[Seq[File]]("gen-tables")
lazy val slickCodeGenTask = (sourceManaged, dependencyClasspath in Compile, runner in Compile, streams) map { (dir, cp, r, s) =>
val outputDir = (dir / "slick").getPath
val url = conf.getString("slick.dbs.default.db.url")
val jdbcDriver = conf.getString("slick.dbs.default.db.driver")
val slickDriver = conf.getString("slick.dbs.default.driver").dropRight(1)
val pkg = "test"
val user = conf.getString("slick.dbs.default.db.user")
val password = conf.getString("slick.dbs.default.db.password")
toError(r.run("slick.codegen.SourceCodeGenerator", cp.files, Array(slickDriver, jdbcDriver, url, outputDir, pkg, user, password), s.log))
val fname = outputDir + s"/$pkg/Tables.scala"
Seq(file(fname))
}
并使用activator gen-tables