I trying to learn how to write RESTful apps in Java using Jersey and Hibernate, and I'm struggling to understand how to handle parent/child type relationships when POSTing data to a Resource. I'm using JSON to exchange data, but I don't think that's particularly relevant to my problem.
The example I'm working with models the relationship between employees and teams. An employee may, or may not, be a member of one team:
GET /team/ - returns a list of teams
POST /team/ - creates a new team
GET /team/1 - returns a list of employees in the team with the ID 1
GET /employee/ - returns a list of employees
POST /employee/ - creates a new employee
GET /employee/1 - returns details about the employee with the ID 1
Behind this I have some Hibernate annotated POJOs: one for team, and one for employee, with a 1-N relationship between the two (remember that an Employee may not be a member of a team!). The same POJOs are also annotated as @XmlRootElements so that JAXB will allow me to pass them to/from the client as JSON.
The properties for the two entities look like this:
Team
Long id;
String name;
String desc;
List<Employee> employees;
Employee
Long id;
Team team;
String name;
String phone;
String email;
All good so far. But I'm struggling to understand how to make an employee a member of a team at creation-time by just passing in a Team ID, rather than passing in a nested team object in my JSON object.
For example, I'd like to be able to call POST /employee/ with a JSON that looks like this:
{
"team_id":"1",
"name":"Fred Bloggs",
"phone":"1234567890",
"email":"[email protected]"
}
But, instead, I have to pass in something like this:
{
"team":{
"id":"1",
}
"name":"Fred Bloggs",
"phone":"1234567890",
"email":"[email protected]"
}
So, my question is, how do others handle creating relationships in JSON/REST without passing around whole object graphs?
Sorry this is such a sketchy question, but as I say, I'm just starting out, and terminology is a problem for me at this stage!