Reputation: 327
There are two set of data: provinces and cities.
The controller for provinces works properly. After posting with this method:
@RequestMapping(method=RequestMethod.POST, value="/provinces")
public void addProvince(@RequestBody Province province) {
provinceService.addProvince(province);
}
and get it with this method:
@RequestMapping("/provinces")
public List<Province> getAllProvinces( ) {
return provinceService.getAllProvinces();
}
the object I posted shows on my browser.
{
"id": "ks",
"name": "Kangso",
"description": "Peace River and So City"
}
However, after posting a city to that province:
@RequestMapping(method=RequestMethod.POST,
value="/provinces/{provinceId}/cites/")
public void addCity(@RequestBody City city,
@PathVariable String provinceId) {
city.setProvince(new Province(provinceId, "", ""));
cityService.addCity(city);
}
with the method in CityService:
public void addCity(City city) {
cityRepository.save(city);
}
and read it with the method:
@RequestMapping("/provinces/{provinceId}/cities")
public List<City> getAllCities(@PathVariable String provinceId) {
return cityService.getAllCities(provinceId);
}
and this request:
The posted object was not showing.
No error came out while compiling or sending the requests, and the RequestMapping for cities worked like other requests:
Mapped "{[/provinces/{provinceId}/cites/],methods=[POST]}"
Mapped "{[/provinces/{provinceId}/cities]}"
Mapped "{[/provinces]}"
Mapped "{[/provinces],methods=[POST]}"
I'm not sure whether the city is properly posted, and now I'm also trying to check what was actually posted in the CityService with eclipse STS.
Upvotes: 0
Views: 831
Reputation: 5049
One issue to start is that your path is /provinces/{provinceId}/cites/
, and should be /provinces/{provinceId}/cities/
. I don't believe that is the core of the issue, however, I do believe that is why you aren't seeing any errors.
I believe that, if your path was correct, you would get an error that the Province
(as defined by new Province(provinceId, "", "")
) is not a managed entity. You can't relate that province to a city, and so on, because it's not persisted. Once persisted, you'd have an ID, and that would allow a relationship to be created.
Your method is creating a new empty Province, and therefore is not doing anything with the provinceId
parameter. You need to take that parameter, and try to get a province object first.
@RequestMapping(method=RequestMethod.POST,
value="/provinces/{provinceId}/cities/")
public void addCity(@RequestBody City city,
@PathVariable String provinceId) {
Province p = provinceService.findOne(provinceId);
if (p != null) {
city.setProvince(p);
cityService.addCity(city);
} else {
// probably should throw a not found error here for the province
}
}
Upvotes: 2