, . . https://coderanch.com/t/628230/framework/Spring-Data-obtain-id-added
TL;DR;
B, . , B entity, A.
Todo, , Comment - .
@Entity
public class Todo {
@OneToMany(mappedBy = "todo", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
private Set<Comment> comments = new HashSet<>();
}
@Entity
public class Comment {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToOne
@JoinColumn(name = "todo_id")
private Todo todo;
}
spring , 2 . TodoRepository CommentRepository, Autowired in.
, POST /api/todos/1/comments, id todo.
@PostMapping(value = "/api/todos/{todoId}/comments")
public ResponseEntity<Resource<Comment>> comments(@PathVariable("todoId") Long todoId,
@RequestBody Comment comment) {
Todo todo = todoRepository.findOne(todoId);
Comment savedComment = commentRepository.save(comment);
todo.addComment(savedComment);
todoRepository.save(todo);
}
Comment. - todo.getComments() Comment, imo, Set.
@PostMapping(value = "/api/todos/{todoId}/comments")
public ResponseEntity<Resource<Comment>> comments(@PathVariable("todoId") Long todoId,
@RequestBody Comment comment) {
Todo todo = todoRepository.findOne(todoId);
todo.addComment(comment);
Todo savedTodo = todoRepository.save(todo);
}