xqtxq xqtxq - 1 year ago 83
Java Question

Response entity and response in client differ

I've got a Spring REST web application. I've got a method which returns a response entity.

@RequestMapping(value = "/shoes", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> getShoes() {

Collection<Shoes> shoes = shoesService.findAll();

ResponseEntity responseEntity = new ResponseEntity<>(shoes, HttpStatus.OK);
return responseEntity;

When I set a breakpoint on the last line, I can see that the
contains a list of the following objects:

Shoes{id=1, localization=Localization{id=1, city='Denver'}, category=Category{id=1, name='wellingtons', group='male'}, size=9}

But when I send the request in client app, I get a JSON, which contains only id and size:

"id": 1,
"size": 9

I wonder why I don't receive localization and category.

Here is the

@Table(name = "shoes")
public class Shoes{

@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private Localization localization;

private Category category;

@Column(name = "size")
private int size;


dur dur
Answer Source

If you have bi-directional associations, you have to declare which object has the role of parent (annotated with JsonManagedReference) and which has the role of child (annotated with JsonBackReference) to break cycles.

You annotated both properties (localization, category) to not be serialized, see JsonBackReference:

Annotation used to indicate that associated property is part of two-way linkage between fields; and that its role is "child" (or "back") link. Value type of the property must be a bean: it can not be a Collection, Map, Array or enumeration. Linkage is handled such that the property annotated with this annotation is not serialized; and during deserialization, its value is set to instance that has the "managed" (forward) link.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download