I cannot figure out how to add an object to a OneToMany relationship using Spring-Data REST when the mapped classes REST Repository is not exported.
I have two classes, Question and Answer. Question has a member variable defined like this:
@OneToMany(mappedBy = "answer", cascade=CascadeType.ALL, orphanRemoval = true)
@LazyCollection(LazyCollectionOption.FALSE)
private List<Answer> answers = new LinkedList<Answer>();
And Answer maps back to Question like this:
@NotNull
@ManyToOne(targetEntity = Question.class)
@JoinColumn(name = "question_id", referencedColumnName = "id")
private Question question;
Because Answer objects are only relevant to the Question they belong to, I've disabled exporting the REST repository:
@RestResource(exported = false)
public interface AnswerRepository extends JpaRepository<Answer, Long> {}
When I fetch a question here: http://localhost:9090/data/questions/7, I get something like this:
{
"creationDate": "2014-09-26T06:36:44.000+0000",
"modificationDate": "2014-09-26T06:36:44.000+0000",
"answers": [],
"_links": {
"self": {
"href": "http://localhost:9090/data/questions/7"
}
}
}
So far so good. Now I want to add an answer like this:
curl -v -X PUT -H "Content-Type: application/json" \
-d "{"answers": [{"value": "Red"}]}" http://localhost:9090/data/questions/7
Unfortunately, at this point I get the following error:
A collection with cascade=\"all-delete-orphan\" was no longer referenced by the owning entity instance: com.example.Question.answers
A brief search of StackOverflow indicates the above error is caused by replacing your collection with another one, orphaning the previous collection. Since all of this code managed by Spring, I don't see how to manipulate my objects to avoid this problem.
This question is similar, however the difference is that in this case the repository is not exported, while in that question it is.