I don t think the accepted answer is correct. See https://coderanch.com/t/628230/framework/Spring-Data-obtain-id-added
tldr;
You should just create a repository for the child B
so you can save the child completely independently from its parent. Once you have the saved B entity
then associate it to its parent A
.
Here is some sample code with Todo
being the parent and Comment
being the child.
@Entity
public class Todo {
@OneToMany(mappedBy = "todo", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
private Set<Comment> comments = new HashSet<>();
// getters/setters omitted.
}
@Entity
public class Comment {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToOne
@JoinColumn(name = "todo_id")
private Todo todo;
// getters/setters omitted.
}
If this was modeled in spring data, you create 2 repositories. TodoRepository
and CommentRepository
which are Autowired
in.
Given a rest endpoint capable of receiving POST /api/todos/1/comments
to associate a new comment with a given todo id.
@PostMapping(value = "/api/todos/{todoId}/comments")
public ResponseEntity<Resource<Comment>> comments(@PathVariable("todoId") Long todoId,
@RequestBody Comment comment) {
Todo todo = todoRepository.findOne(todoId);
// SAVE the comment first so its filled with the id from the DB.
Comment savedComment = commentRepository.save(comment);
// Associate the saved comment to the parent Todo.
todo.addComment(savedComment);
// Will update the comment with todo id FK.
todoRepository.save(todo);
// return payload...
}
If instead you did the below and saved the supplied parameter comment
. The only way to get the new comment is iterate through todo.getComments()
and find the supplied comment
which is annoying and impractical imo if the collection is a Set
.
@PostMapping(value = "/api/todos/{todoId}/comments")
public ResponseEntity<Resource<Comment>> comments(@PathVariable("todoId") Long todoId,
@RequestBody Comment comment) {
Todo todo = todoRepository.findOne(todoId);
// Associate the supplied comment to the parent Todo.
todo.addComment(comment);
// Save the todo which will cascade the save into the child
// Comment table providing cascade on the parent is set
// to persist or all etc.
Todo savedTodo = todoRepository.save(todo);
// You cant do comment.getId
// Hibernate creates a copy of comment and persists it or something.
// The only way to get the new id is iterate through
// todo.getComments() and find the matching comment which is
// impractical especially if the collection is a set.
// return payload...
}