我正在尝试使用Slick在MySql表中进行简单插入。如您在下面的调试输出中看到的,代码将被执行,但是值不会被插入数据库。

这是Database.scala代码:

//import slick.jdbc.JdbcBackend._
import slick.dbio.DBIOAction
import slick.driver.MySQLDriver.api._
import slick.lifted.TableQuery

import java.sql.Timestamp

class Database {
  val url = "jdbc:mysql://username=root:password=xxx@localhost/playdb"
  val db = Database.forURL(url, driver = "com.mysql.jdbc.Driver")
  val emrepo = TableQuery[EmailMessageTable]

  override def finalize() {
    db.close()
    super.finalize()
  }


protected class EmailMessageTable(tag: Tag) extends Table[EmailMessage](tag, "email_message") {

  def id      = column[Option[Long]]("id", O.AutoInc, O.PrimaryKey)
  def email   = column[String]("email")
  def subject = column[String]("subject")
  def body    = column[String]("body")
  def datain  = column[Timestamp]("datain")
  def email_id= column[Long]("email_id")

  def * = (id, email, subject, body, datain, email_id) <> ((EmailMessage.apply _).tupled, EmailMessage.unapply)
  def ? = (id.get.?, email.?, subject.?, body.?, datain.?, email_id.?).shaped.<>({ r => import r._; _1.map(_ =>
    EmailMessage.tupled((_1, _2.get, _3.get, _4.get, _5.get, _6.get))) }, (_: Any) =>
    throw new Exception("Inserting into ? projection not supported."))
}

  def insert(m: EmailMessage) {
    db.run(
        (emrepo += m)
    )
  }
}


调用代码:

 def toDatabase(m: EmailMessage): EmailMessage = {
    val db = new Database()
    println("HIT")
    db.insert(m)
    println("HIT 2")
    println(m)
    m
  }


插入数据库中的case class对象:

import java.sql.Timestamp

case class EmailMessage(
  id: Option[Long],
  email: String,
  subject:String,
  body:String,
  datain: Timestamp,
  email_id: Long
)


DEBUG输出,显示对Slick的调用以及Slick调试输出:

HIT
2016-09-06 16:08:41:563 -0300 [run-main-0] DEBUG slick.compiler.QueryCompiler - Source:
| TableExpansion
|   table s2: Table email_message
|   columns: TypeMapping
|     0: ProductNode
|       1: Path s2.id : Option[Long']
|       2: Path s2.email : String'
|       3: Path s2.subject : String'
|       4: Path s2.body : String'
|       5: Path s2.datain : java.sql.Timestamp'
|       6: Path s2.email_id : Long'

2016-09-06 16:08:41:587 -0300 [run-main-0] DEBUG slick.compiler.AssignUniqueSymbols - Detected features: UsedFeatures(false,true,false,false)
2016-09-06 16:08:41:597 -0300 [run-main-0] DEBUG slick.compiler.QueryCompiler - After phase assignUniqueSymbols:
| TableExpansion
|   table s3: Table email_message
|   columns: TypeMapping
|     0: ProductNode
|       1: Path s3.id : Option[Long']
|       2: Path s3.email : String'
|       3: Path s3.subject : String'
|       4: Path s3.body : String'
|       5: Path s3.datain : java.sql.Timestamp'
|       6: Path s3.email_id : Long'

2016-09-06 16:08:41:605 -0300 [run-main-0] DEBUG slick.compiler.QueryCompiler - After phase inferTypes: (no change)
2016-09-06 16:08:41:624 -0300 [run-main-0] DEBUG slick.compiler.QueryCompiler - After phase insertCompiler:
| ResultSetMapping : Vector[(String', String', String', java.sql.Timestamp', Long')]
|   from s5: Insert allFields=[id, email, subject, body, datain, email_id] : (String', String', String', java.sql.Timestamp', Long')
|     table s6: Table email_message : Vector[@t4<UnassignedType>]
|     linear: ProductNode : (String', String', String', java.sql.Timestamp', Long')
|       1: Path s6.email : String'
|       2: Path s6.subject : String'
|       3: Path s6.body : String'
|       4: Path s6.datain : java.sql.Timestamp'
|       5: Path s6.email_id : Long'
|   map: TypeMapping : Mapped[(Option[Long'], String', String', String', java.sql.Timestamp', Long')]
|     0: ProductNode : (Option[Long'], String', String', String', java.sql.Timestamp', Long')
|       1: InsertColumn id : Option[Long']
|       2: InsertColumn email : String'
|         0: Path s5._1 : String'
|       3: InsertColumn subject : String'
|         0: Path s5._2 : String'
|       4: InsertColumn body : String'
|         0: Path s5._3 : String'
|       5: InsertColumn datain : java.sql.Timestamp'
|         0: Path s5._4 : java.sql.Timestamp'
|       6: InsertColumn email_id : Long'
|         0: Path s5._5 : Long'

2016-09-06 16:08:41:638 -0300 [run-main-0] DEBUG slick.compiler.CodeGen - Compiling server-side and mapping with server-side:
| Insert allFields=[id, email, subject, body, datain, email_id] : (String', String', String', java.sql.Timestamp', Long')
|   table s6: Table email_message : Vector[@t4<UnassignedType>]
|   linear: ProductNode : (String', String', String', java.sql.Timestamp', Long')
|     1: Path s6.email : String'
|     2: Path s6.subject : String'
|     3: Path s6.body : String'
|     4: Path s6.datain : java.sql.Timestamp'
|     5: Path s6.email_id : Long'

2016-09-06 16:08:41:673 -0300 [run-main-0] DEBUG slick.relational.ResultConverterCompiler - Compiled ResultConverter
| TypeMappingResultConverter
|   child: ProductResultConverter
|     1: CompoundResultConverter
|     2: SpecializedJdbcResultConverter$$anon$1 idx=1, name=email : String'
|     3: SpecializedJdbcResultConverter$$anon$1 idx=2, name=subject : String'
|     4: SpecializedJdbcResultConverter$$anon$1 idx=3, name=body : String'
|     5: SpecializedJdbcResultConverter$$anon$1 idx=4, name=datain : java.sql.Timestamp'
|     6: BaseResultConverter$mcJ$sp idx=5, name=email_id : Long'

2016-09-06 16:08:41:675 -0300 [run-main-0] DEBUG slick.compiler.CodeGen - Compiled server-side to:
| CompiledStatement "insert into `email_message` (`email`,`subject`,`body`,`datain`,`email_id`)  values (?,?,?,?,?)" : (String', String', String', java.sql.Timestamp', Long')

2016-09-06 16:08:41:681 -0300 [run-main-0] DEBUG slick.compiler.QueryCompiler - After phase codeGen:
| ResultSetMapping : Vector[(String', String', String', java.sql.Timestamp', Long')]
|   from s5: CompiledStatement "insert into `email_message` (`email`,`subject`,`body`,`datain`,`email_id`)  values (?,?,?,?,?)" : (String', String', String', java.sql.Timestamp', Long')
|   map: CompiledMapping : Mapped[(Option[Long'], String', String', String', java.sql.Timestamp', Long')]
|     converter: TypeMappingResultConverter
|       child: ProductResultConverter
|         1: CompoundResultConverter
|         2: SpecializedJdbcResultConverter$$anon$1 idx=1, name=email : String'
|         3: SpecializedJdbcResultConverter$$anon$1 idx=2, name=subject : String'
|         4: SpecializedJdbcResultConverter$$anon$1 idx=3, name=body : String'
|         5: SpecializedJdbcResultConverter$$anon$1 idx=4, name=datain : java.sql.Timestamp'
|         6: BaseResultConverter$mcJ$sp idx=5, name=email_id : Long'

2016-09-06 16:08:41:682 -0300 [run-main-0] DEBUG slick.compiler.QueryCompilerBenchmark - ------------------- Phase: Time ---------
2016-09-06 16:08:41:702 -0300 [run-main-0] DEBUG slick.compiler.QueryCompilerBenchmark -       assignUniqueSymbols:   32,729098 ms
2016-09-06 16:08:41:703 -0300 [run-main-0] DEBUG slick.compiler.QueryCompilerBenchmark -                inferTypes:    7,924984 ms
2016-09-06 16:08:41:703 -0300 [run-main-0] DEBUG slick.compiler.QueryCompilerBenchmark -            insertCompiler:   18,786989 ms
2016-09-06 16:08:41:703 -0300 [run-main-0] DEBUG slick.compiler.QueryCompilerBenchmark -                   codeGen:   57,406605 ms
2016-09-06 16:08:41:704 -0300 [run-main-0] DEBUG slick.compiler.QueryCompilerBenchmark -                     TOTAL:  116,847676 ms
2016-09-06 16:08:41:709 -0300 [run-main-0] DEBUG slick.backend.DatabaseComponent.action - #1: SingleInsertAction [insert into `email_message` (`email`,`subject`,`body`,`datain`,`email_id`)  values (?,?,?,?,?)]
HIT 2
EmailMessage(None,fernando@localhost,Me,teste daqui para ali rapido.,2016-09-06 16:08:41.099,1)
2016-09-06 16:08:41:746 -0300 [AsyncExecutor.default-1] DEBUG slick.jdbc.JdbcBackend.statement - Preparing statement: insert into `email_message` (`email`,`subject`,`body`,`datain`,`email_id`)  values (?,?,?,?,?)
[success] Total time: 18 s, completed 06/09/2016 16:08:41


该值不会插入到数据库中。为什么?

最佳答案

最可能的情况是语句“ db.insert(m)”是异步的(它返回一个Future),并且您在Future结束之前已完成程序,请尝试进行睡眠或等待Future结束。

您可以尝试如下操作:

val result = db.insert(m)
Await.result(result, Duration.Inf)
...


我遇到了类似的问题,在此之前您可以在这里看到:How to configure Slick 3.1.1 for PostgreSQL? It seems to ignore my config parameters while running plain sql queries

关于mysql - slick db.run不插入操作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39356471/

10-13 08:53