doublemc doublemc - 4 years ago 98
Java Question

Controller returns JSON containing two entities instead of one

Here is my controller:

// CREATE NEW TODOITEM FROM SENT JSON
@PostMapping("/todos")
@ResponseStatus(HttpStatus.OK)
public ToDoItem newToDo(
@RequestBody ToDoItem toDoItem,
Principal principal
) {
User currentUser = userService.findLoggedInUser(principal);
return toDoItemService.addToDo(toDoItem, currentUser);
}


toDoItemService.addToDo:

public ToDoItem addToDo(ToDoItem toDoItem, User user) {
String toDoTitle = toDoItem.getTitle();
LocalDate toDoDueDate = toDoItem.getDueDate();
ToDoItem newToDo = new ToDoItem(user, toDoTitle, toDoDueDate);
return toDoItemRepository.save(newToDo);
}


ToDoItem entity (ommited constructors and getters/setters):

@Entity
@Table (name = "TO_DO_ITEMS")
public class ToDoItem extends BaseEntity {

@Column(name = "TITLE", nullable = false)
private String title;

@Column(name = "COMPLETED")
private boolean completed;

@Column(name = "DUE_DATE", nullable = false)
@Convert(converter = LocalDateAttributeConverter.class)
@JsonDeserialize(using = LocalDateDeserializer.class)
@JsonSerialize(using = LocalDateSerializer.class)
private LocalDate dueDate;

// a ToDoItem is only associated with one user
@ManyToOne(cascade=CascadeType.PERSIST)
@JoinColumn(name = "USER_ID")
private User user;


And my toDoItemRepository just extends CrudRepository.

When I shoot:

{
"title":"testtodo3",
"dueDate": [
2015,
12,
6
]
}


at
localhost:8080/todos
I get this:

{
"id": 1,
"title": "testtodo3",
"completed": false,
"dueDate": [
2015,
12,
6
],
"user": {
"id": 1,
"username": "gruchacz",
"password": "password",
"email": "newUser@example.com"
}
}


Why are all the details of my User visible when I'm returning only ToDoItem (as save from CrudRepository does)? I know my ToDoItem is linked to User, but i would like it to return only ID, title, completed and dueDate WITHOUT user data? I know I could override toString method in ToDoItem entity and return a String from that controller but it's very unelegant and would prefer to retunr just ToDoItem and jackson to handle conversion to JSON.

Answer Source

There are two options for you:

1: add @JsonIgnore on User field in ToDoItem, Jackson will ignore it, or

2: Use DTO pattern, create another value object to deliver it back on HTTP layer.

I will recommend second option

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