slick: [ошибка] неправильное количество аргументов типа для slick.driver.H2Driver.simple.Query, должно быть 3

Привет, я пытаюсь запустить пример hello-slick из шаблона активатора безопасного типа, когда запускаю его как мой собственный проект sbt, он дает мне ошибку, я просто копирую код, но он дает мне ошибку

вот мой код

HelloSlick.scala

import scala.slick.driver.H2Driver.simple._

// The main application
object HelloSlick extends App {

  // The query interface for the Suppliers table
  val suppliers: TableQuery[Suppliers] = TableQuery[Suppliers]

  // the query interface for the Coffees table
  val coffees: TableQuery[Coffees] = TableQuery[Coffees]

  // Create a connection (called a "session") to an in-memory H2 database
  val db = Database.forURL("jdbc:h2:mem:hello", driver = "org.h2.Driver")
  db.withSession { implicit session =>

    // Create the schema by combining the DDLs for the Suppliers and Coffees
    // tables using the query interfaces
    (suppliers.ddl ++ coffees.ddl).create


    /* Create / Insert */

    // Insert some suppliers
    suppliers += (101, "Acme, Inc.", "99 Market Street", "Groundsville", "CA", "95199")
    suppliers += ( 49, "Superior Coffee", "1 Party Place", "Mendocino", "CA", "95460")
    suppliers += (150, "The High Ground", "100 Coffee Lane", "Meadows", "CA", "93966")

    // Insert some coffees (using JDBC's batch insert feature)
    val coffeesInsertResult: Option[Int] = coffees ++= Seq (
      ("Colombian",         101, 7.99, 0, 0),
      ("French_Roast",       49, 8.99, 0, 0),
      ("Espresso",          150, 9.99, 0, 0),
      ("Colombian_Decaf",   101, 8.99, 0, 0),
      ("French_Roast_Decaf", 49, 9.99, 0, 0)
    )

    val allSuppliers: List[(Int, String, String, String, String, String)] =
      suppliers.list

    // Print the number of rows inserted
    coffeesInsertResult foreach { numRows =>
      println(s"Inserted $numRows rows into the Coffees table")
    }


    /* Read / Query / Select */

    // Print the SQL for the Coffees query
    println("Generated SQL for base Coffees query:\n" + coffees.selectStatement)

    // Query the Coffees table using a foreach and print each row
    coffees foreach { case (name, supID, price, sales, total) =>
      println("  " + name + "\t" + supID + "\t" + price + "\t" + sales + "\t" + total)
    }


    /* Filtering / Where */

    // Construct a query where the price of Coffees is > 9.0
    val filterQuery: Query[Coffees, (String, Int, Double, Int, Int)] =
      coffees.filter(_.price > 9.0)

    println("Generated SQL for filter query:\n" + filterQuery.selectStatement)

    // Execute the query
    println(filterQuery.list)


    /* Update */

    // Construct an update query with the sales column being the one to update
    val updateQuery: Query[Column[Int], Int] = coffees.map(_.sales)

    // Print the SQL for the Coffees update query
    println("Generated SQL for Coffees update:\n" + updateQuery.updateStatement)

    // Perform the update
    val numUpdatedRows = updateQuery.update(1)

    println(s"Updated $numUpdatedRows rows")


    /* Delete */

    // Construct a delete query that deletes coffees with a price less than 8.0
    val deleteQuery: Query[Coffees,(String, Int, Double, Int, Int)] =
      coffees.filter(_.price < 8.0)

    // Print the SQL for the Coffees delete query
    println("Generated SQL for Coffees delete:\n" + deleteQuery.deleteStatement)

    // Perform the delete
    val numDeletedRows = deleteQuery.delete

    println(s"Deleted $numDeletedRows rows")


    /* Selecting Specific Columns */

    // Construct a new coffees query that just selects the name
    val justNameQuery: Query[Column[String], String] = coffees.map(_.name)

    println("Generated SQL for query returning just the name:\n" +
      justNameQuery.selectStatement)

    // Execute the query
    println(justNameQuery.list)


    /* Sorting / Order By */

    val sortByPriceQuery: Query[Coffees, (String, Int, Double, Int, Int)] =
      coffees.sortBy(_.price)

    println("Generated SQL for query sorted by price:\n" +
      sortByPriceQuery.selectStatement)

    // Execute the query
    println(sortByPriceQuery.list)


    /* Query Composition */

    val composedQuery: Query[Column[String], String] =
      coffees.sortBy(_.name).take(3).filter(_.price > 9.0).map(_.name)

    println("Generated SQL for composed query:\n" +
      composedQuery.selectStatement)

    // Execute the composed query
    println(composedQuery.list)


    /* Joins */

    // Join the tables using the relationship defined in the Coffees table
    val joinQuery: Query[(Column[String], Column[String]), (String, String)] = for {
      c <- coffees if c.price > 9.0
      s <- c.supplier
    } yield (c.name, s.name)

    println("Generated SQL for the join query:\n" + joinQuery.selectStatement)

    // Print the rows which contain the coffee name and the supplier name
    println(joinQuery.list)


    /* Computed Values */

    // Create a new computed column that calculates the max price
    val maxPriceColumn: Column[Option[Double]] = coffees.map(_.price).max

    println("Generated SQL for max price column:\n" + maxPriceColumn.selectStatement)

    // Execute the computed value query
    println(maxPriceColumn.run)


    /* Manual SQL / String Interpolation */

    // Required import for the sql interpolator
    import scala.slick.jdbc.StaticQuery.interpolation

    // A value to insert into the statement
    val state = "CA"

    // Construct a SQL statement manually with an interpolated value
    val plainQuery = sql"select SUP_NAME from SUPPLIERS where STATE = $state".as[String]

    println("Generated SQL for plain query:\n" + plainQuery.getStatement)

    // Execute the query
    println(plainQuery.list)

  }
}

Таблицы.scala

import scala.slick.driver.H2Driver.simple._
import scala.slick.lifted.{ProvenShape, ForeignKeyQuery}

// A Suppliers table with 6 columns: id, name, street, city, state, zip
class Suppliers(tag: Tag)
  extends Table[(Int, String, String, String, String, String)](tag, "SUPPLIERS") {

  // This is the primary key column:
  def id: Column[Int] = column[Int]("SUP_ID", O.PrimaryKey)
  def name: Column[String] = column[String]("SUP_NAME")
  def street: Column[String] = column[String]("STREET")
  def city: Column[String] = column[String]("CITY")
  def state: Column[String] = column[String]("STATE")
  def zip: Column[String] = column[String]("ZIP")

  // Every table needs a * projection with the same type as the table's type parameter
  def * : ProvenShape[(Int, String, String, String, String, String)] =
    (id, name, street, city, state, zip)
}

// A Coffees table with 5 columns: name, supplier id, price, sales, total
class Coffees(tag: Tag)
  extends Table[(String, Int, Double, Int, Int)](tag, "COFFEES") {

  def name: Column[String] = column[String]("COF_NAME", O.PrimaryKey)
  def supID: Column[Int] = column[Int]("SUP_ID")
  def price: Column[Double] = column[Double]("PRICE")
  def sales: Column[Int] = column[Int]("SALES")
  def total: Column[Int] = column[Int]("TOTAL")

  def * : ProvenShape[(String, Int, Double, Int, Int)] =
    (name, supID, price, sales, total)

  // A reified foreign key relation that can be navigated to create a join
  def supplier: ForeignKeyQuery[Suppliers, (Int, String, String, String, String, String)] = 
    foreignKey("SUP_FK", supID, TableQuery[Suppliers])(_.id)
}

build.sbt

name :="hellos"

version :="1.0"

scalaVersion := "2.11.1"

mainClass in Compile := Some("HelloSlick")

libraryDependencies ++= List(
  "com.typesafe.slick" %% "slick" % "2.1.0",
  "org.slf4j" % "slf4j-nop" % "1.6.4",
  "com.h2database" % "h2" % "1.3.170"
)

resolvers += "typesafe" at "http://repo.typesafe.com/typesafe/releases/"

когда я запускаю его как проект sbt, он выдает следующие ошибки

[error] /opt/progrmas/sbt/hellos/src/main/scala/HelloSlick.scala:60: wrong number of type arguments for slick.driver.H2Driver.simple.Query, should be 3
[error]     val filterQuery: Query[Coffees, (String, Int, Double, Int, Int)] =
[error]                      ^
[error] /opt/progrmas/sbt/hellos/src/main/scala/HelloSlick.scala:72: wrong number of type arguments for slick.driver.H2Driver.simple.Query, should be 3
[error]     val updateQuery: Query[Column[Int], Int] = coffees.map(_.sales)
[error]                      ^
[error] /opt/progrmas/sbt/hellos/src/main/scala/HelloSlick.scala:86: wrong number of type arguments for slick.driver.H2Driver.simple.Query, should be 3
[error]     val deleteQuery: Query[Coffees,(String, Int, Double, Int, Int)] =
[error]                      ^
[error] /opt/progrmas/sbt/hellos/src/main/scala/HelloSlick.scala:101: wrong number of type arguments for slick.driver.H2Driver.simple.Query, should be 3
[error]     val justNameQuery: Query[Column[String], String] = coffees.map(_.name)
[error]                        ^
[error] /opt/progrmas/sbt/hellos/src/main/scala/HelloSlick.scala:112: wrong number of type arguments for slick.driver.H2Driver.simple.Query, should be 3
[error]     val sortByPriceQuery: Query[Coffees, (String, Int, Double, Int, Int)] =
[error]                           ^
[error] /opt/progrmas/sbt/hellos/src/main/scala/HelloSlick.scala:124: wrong number of type arguments for slick.driver.H2Driver.simple.Query, should be 3
[error]     val composedQuery: Query[Column[String], String] =
[error]                        ^
[error] /opt/progrmas/sbt/hellos/src/main/scala/HelloSlick.scala:137: wrong number of type arguments for slick.driver.H2Driver.simple.Query, should be 3
[error]     val joinQuery: Query[(Column[String], Column[String]), (String, String)] = for {
[error]                    ^
[error] 7 errors found
[error] (compile:compile) Compilation failed
[error] Total time: 15 s, completed Aug 25, 2014 1:20:34 AM
> 

пожалуйста, помогите, я новичок в slick, я просто получаю помощь от учебника и получаю эти ошибки, это даже не мой собственный код, вот ссылка на шаблон http://typesafe.com/activator/template/hello-slick


person swaheed    schedule 25.08.2014    source источник


Ответы (2)


Вы пытаетесь использовать версию шаблона Slick 2.0 с Slick 2.1. Query имеет два параметра типа до Slick 2.0 и три в Slick 2.1. Ссылки на правильные официальные шаблоны приведены в руководстве (http://slick.typesafe.com/doc/2.1.0/gettingstarted.html). Обратите внимание, что все аннотации типов в шаблоне показаны в образовательных целях. Если вы их не укажете, код все равно будет компилироваться и должен быть совместим между версиями 2.0 и 2.1.

person szeiger    schedule 25.08.2014
comment
И что я должен делать ?? - person swaheed; 25.08.2014
comment
я пробовал с slick 2.0.2, так как он использовался в шаблоне, но это дает мне ошибку com.typesafe.slick %% slick % 2.0.2, поэтому после этого stackoverflow.com/questions/25475514/ ответ мой вопрос был решен, но это дает мне 7 ошибку о неправильных аргументах - person swaheed; 25.08.2014
comment
Я не могу добавить к этому больше того, что уже было сказано по другому вопросу. Если вы хотите, чтобы код на основе Slick 2.0 из старого шаблона работал, используйте Scala 2.10.4 с Slick 2.0.3. Если вы хотите использовать Scala 2.11, переключитесь на Slick 2.1.0 и используйте код из нового шаблона (typesafe.com/activator/template/hello-slick-2.1). Шаблон Activator — это стандартный проект sbt (с дополнительной обучающей страницей в нем), так что вы можете скопировать его 1:1. Не забудьте сделать reload в sbt, если вы измените скрипт сборки .sbt. - person szeiger; 28.08.2014
comment
я использую код того же шаблона, который вы упомянули, но я использую scala 2.11, и когда я добавляю slick 2.0.2 в свой файл сборки, это дает мне ошибку при неразрешенной зависимости - person swaheed; 28.08.2014

Образец представляет собой код 2.0, а вы используете 2.1. В руководстве по обновлению рассказывается, как выполнить обновление с 2.0 до 2.1:

Запрос теперь принимает 3 параметра типа вместо двух. Query[T,E] в версии 2.0 эквивалентен Query[T,E,Seq] в Slick 2.1. Третий параметр — это тип коллекции, который будет возвращен при выполнении запроса с использованием .run, который всегда возвращал Seq в Slick 2.0.

Кажется, все, что вам нужно сделать, это добавить Seq в качестве третьего параметра:

 Query[Coffees, (String, Int, Double, Int, Int), Seq]
person Suma    schedule 03.02.2015