第一次使用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]]
我是否正确地做到了这一点?无视错误,我不这么认为。如何合并save
和insertIntoDB
?
另外,如何测试添加数据而不必每次都卷曲?
感谢您的帮助!
编辑:添加了架构+新错误
答案 0 :(得分:2)
问题是您在插入时使用了错误的名称/键:
{}
问题是:
task.id
on
)与id
(def 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()
}
}
)您可以重写为:
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