Reputation: 1154
After spending much of the day on this I'm missing something obvious with @ManyToOne and @OneToMany mappings.
I have two classes which I want to expose via REST, a Project class and a Milestone Class. Each Project can have many milestones associated.
@Entity
public class Project {
@Id
@Column(name="project_id")
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@OneToMany
private List<Milestone> milestones = new ArrayList<>();
private String name;
private String description;
// Getter and setters removed for brevity
}
@Entity
public class Milestone {
@Id
@Column(name="milestone_id")
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
private String description;
@ManyToOne
@JoinColumn(name="project_id")
private Project project;
// Getter and setters removed for brevity
}
My Repository classes are:
public interface ProjectRepository extends JpaRepository<Project, Long> {
List<Project> findByName(@Param("name") String name);
}
public interface MilestoneRepository extends JpaRepository<Milestone, Long> {
List<Milestone> findByName(@Param("name") String name);
}
Updating the URI on Projects with a post to localhost:8080/projects/1/milestones doesn't work, I can however create new projects and milestones without any linking.
My goal is to post Project entries and then subsequently post Milestone entries over time, this would update the list of associated Milestones on the Project class.
Any idea what could be wrong?
UPDATE:
Using Python's HTTPIE utility I did the following to create an initial project:
http post localhost:8080/projects name="test" description="test"
Then I do the following to assign a milestone:
http post localhost:8080/milestones name="test" description="test" project="http://localhost:8080/projects/1"
The response back is:
HTTP/1.1 201
Content-Type: application/json
Location: http://localhost:8080/milestones/1
Transfer-Encoding: chunked
{
"_links": {
"milestone": {
"href": "http://localhost:8080/milestones/1"
},
"project": {
"href":"http://localhost:8080/milestones/1/project"
},
"self":{
"href":"http://localhost:8080/milestones/1"
}
},
"description":"test",
"name":"test"
}
In the database the PROJECT_ID column is null
Upvotes: 0
Views: 85
Reputation: 23246
You need to make a POST to
http://localhost:8080/milestones
which includes a link to the associated project via its resource URL:
{
"name": "milestone name",
"description": "milstone description",
"project": "http://localhost:8080/projects/1"
}
Upvotes: 1