@RequestBody 表記を使用して、フロントエンドから JSON を取得し、タスクをデータベースに追加します。こんな感じ
@RequestMapping(method = RequestMethod.POST)
public @ResponseBody ResponseEntity<Task> addTask(@RequestBody Task task) {
try {
tService.saveTask(task);
return new ResponseEntity<Task>(task, HttpStatus.OK);
}
catch (final Exception e) {
return new ResponseEntity<Task>(HttpStatus.BAD_REQUEST);
}
}
これは初めてうまく機能します - タスクはデータベースで作成され、200 コードが返されます。しかし、タスクを追加し続けると、400 が返され、
The request sent by the client was syntactically incorrect.
Task.java コード:
@Entity
@Table(name = "task")
public class Task {
private int id;
private String content;
private Participant taskKeeper;
private Event taskEventKeeper;
private Boolean isDone;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "task_id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name = "content", length = 500, nullable = false)
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Column(name = "isDone", nullable = false)
public Boolean getIsDone() { return isDone; }
public void setIsDone(Boolean isDone) { this.isDone = isDone; }
@ManyToOne
@JsonBackReference("task-event")
@JoinColumn(name = "event_id")
public Event getTaskEventKeeper() {
return taskEventKeeper;
}
public void setTaskEventKeeper(Event taskEventKeeper) {
this.taskEventKeeper = taskEventKeeper;
}
@ManyToOne
@JoinColumn(name = "participant_id")
public Participant getTaskKeeper() {
return taskKeeper;
}
public void setTaskKeeper(Participant taskKeeper) {
this.taskKeeper = taskKeeper;
}
public Task(String content) {
isDone = false;
this.content = content;
}
public Task(String content, Participant taskKeeper, Event taskEventKeeper) {
this.content=content;
this.taskEventKeeper=taskEventKeeper;
this.taskKeeper=taskKeeper;
this.isDone=false;
}
public Task() {
isDone=false;
}
@Override
public String toString() {
return "{" +
"\"id\":" + id +
", \"content\":\"" + content + '\"' +
'}';
}
}
クライアントからの JSON は常に次のようになります。
{"taskEventKeeper":{"id":3},"taskKeeper":{"id":1},"content":"Bazinga"}
これを取り除く方法は?