scala slick不会保留数据

时间:2017-06-08 13:30:33

标签: scala playframework slick

我有以下代码不起作用...不工作意味着在这种情况下它不会在数据库中持久化....

DTO / DAO

  def createChangelogEntry(changeLog: ChangelogModel): Future[ChangelogModel] = {
    println("..........................................")
    println(changeLog)

    val entry =
      (changelogs returning changelogs.map(_.id)
        into ((log,id) => log.copy(id=Some(id)))
        ) += ChangelogModel(None, changeLog.createdat, changeLog.text)

    db.run(entry)
  }

在这种情况下会出现什么问题?匹配模型工作正常...

UUpdate:

SQL:

CREATE TABLE Changelog (
  id BIGINT(255) NOT NULL,
  createdat DATETIME NOT NULL,
  text text NOT NULL
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

我的模特:

package models

import java.sql.Date

import play.api.libs.json.{JsValue, Json, Writes}

/**
  * Created by Felix Hohlwegler on 08.06.2017.
  */
case class ChangelogModel(
                           id: Option[Int] = None,
                           createdat: String,
                           text: String
                         )

object ChangelogModel {
  implicit val changelogFormat = Json.format[ChangelogModel]
}

控制器功能:

package controllers

import javax.inject.{Inject, Singleton}

import dto.changelogDTO
import models.{ChangelogModel, ProcessTemplatesModel}
import play.api.libs.json.{JsError, JsSuccess, Json}
import play.api.mvc.{Action, AnyContent, Controller, Request}

import scala.concurrent.Future

/**
  * Created by Felix Hohlwegler on 08.06.2017.
  */
@Singleton
class Changelogs @Inject()(changelogDTO: changelogDTO) extends Controller {

  def createChangelogEntry = Action { implicit request =>
    request.body.asJson.map(_.validate[ChangelogModel] match {
      case JsSuccess(process, _) =>
        changelogDTO.createChangelogEntry(process)
      case err@JsError(_) => BadRequest("TEST")
      case _ => BadRequest("fail to create Counter")
    }).getOrElse(BadRequest("Failure tu create Counter"))
    Ok("s")
  }
}

1 个答案:

答案 0 :(得分:1)

一个问题是您没有等待从控制器完成插入操作:

// Problem
case JsSuccess(process, _) => changelogDTO.createChangelogEntry(process)

您应该映射未来并异步返回其结果:

// Do this
case JsSuccess(process, _) => changelogDTO.createChangelogEntry(process).map(model => Ok(Json.toJson(model))

然而,这意味着您将需要所有其他案例来返回期货,并且您必须通过异步将结果操作更改为。我就是这样做的:

def createChangelogEntry = Action.async(parse.json) { implicit request =>
  request.body.validate[ChangelogModel].fold(
    errors => Future(BadRequest(JsError.toJson(errors))),
    changelogModel => changelogDTO.createChangelogEntry(changelogModel).map(model => Ok(Json.toJson(model))
  )
}

与此同时,您可能会发现只需将当前插入包装在Await.result中就可以更轻松地进行调试:

import scala.concurrent.duration._

case JsSuccess(process, _) => 
  val model = Await.result(changelogDTO.createChangelogEntry(process), 5 seconds)
  Ok("We inserted the thing")