玩!框架/ Anorm:将数据转换为JSON并存储到DB中

时间:2016-04-14 03:22:43

标签: json scala playframework anorm

第一次使用play框架,我正在努力将我转换为JSON的数据保存到我在框架中建立的数据库中。

以下是我正在尝试的内容:

Controller

//Write converter to convert our model data to JSON
implicit val taskWrites: Writes[Task] = (
    (JsPath \ "id").write[Int] and
    (JsPath \ "name").write[String] and
    (JsPath \ "description").write[String] and
    (JsPath \ "group").write[String]
    )(unlift(Task.unapply))



//saving tasks in JSON format. Returning OK if success.
def saveTask = Action(BodyParsers.parse.json) { request =>
    val taskResult = request.body.validate[Task]
    taskResult.fold(
        errors => {
            BadRequest(Json.obj("status" -> "KO", "Message" -> JsError.toJson(errors)))
        },
        task => {
            Task.save(task)
            //ERROR HERE: Task.insertIntoDB(task)
            Ok(Json.obj("status" -> "Ok", "Message" -> ("Task '" +task.name+ "' saved")))
        }
    )
}

Model

case class Task(id: Int, name: String, description: String, group: String)

var list: List[Task] = Nil

//define a parser that will transform a JDBC ResultSet into a Task value.
val task = {
    get[Int]("id") ~
    get[String]("name") ~
    get[String]("description") ~
    get[String]("group") map {
        case id~name~description~group => Task(id, name, description, group)
    }

}

def save(task: Task) = {
    list = list ::: List(task)
}

def insertIntoDB(task: Task){
    DB.withConnection { implicit c =>
        SQL("insert into task (id, name, description, groupname) values ({task.id, task.name, task.description, task.group})").on(
            'id -> task.id,
            'name -> task.name,
            'description -> task.description,
            'groupname -> task.group
            ).executeUpdate()
    }
}

我正在使用H2数据库引擎

evolutions/default/1.sql

#Tasks Schema

# ---- !Ups
CREATE SEQUENCE task_id_seq;
CREATE TABLE task (
    id integer NOT NULL DEFAULT nextval('task_id_seq'),
    name varchar(255),
    description varchar(255),
    groupname varchar(255)
);

# ---- !Downs
DROP SEQUENCE task_id_seq;
DROP TABLE task;

但是当我尝试添加新任务时:

curl --include --request POST --header "content-type: application/json" --data '{"id":4, "name": "test5", "description": "testdesc1","group": "groupc"}' http://localhost:9000/tasks

我收到错误:

[JdbcSQLException: Syntax error in SQL statement "INSERT INTO TASK (ID, NAME, DESCRIPTION, GROUPNAME) VALUES ( [*]"; expected "), DEFAULT, NOT, EXISTS, INTERSECTS"; SQL statement: insert into task (id, name, description, groupname) values ( [42001-191]]

我是否正确地做到了这一点?无视错误,我不这么认为。如何合并saveinsertIntoDB

另外,如何测试添加数据而不必每次都卷曲?

感谢您的帮助!

编辑:添加了架构+新错误

1 个答案:

答案 0 :(得分:2)

问题是您在插入时使用了错误的名称/键:

您的代码:

{}

问题是:

  1. 插入模板错误。假设对每个变量使用task.id
  2. 模板中使用的密钥(on)与iddef insertIntoDB(task: Task) { DB.withConnection { implicit c => SQL("insert into task (id, name, description, groupname) values ({id}, {name}, {description}, {groupname})").on( 'id -> task.id, 'name -> task.name, 'description -> task.description, 'groupname -> task.group ).executeUpdate() } }
  3. 中使用的密钥不匹配

    您可以重写为:

    def insertIntoDB(task: Task) {
      DB.withConnection { implicit c =>
        SQL("insert into task (id, name, description, groupname) values (${task.id}, ${task.name}, ${task.description}, ${task.group})").executeUpdate()
      }
    }
    

    或者甚至可以将其缩写为:

    {{1}}

    我强烈建议你在这里阅读Anorm文档:

    https://www.playframework.com/documentation/2.5.x/ScalaAnorm