Reputation: 183
when I create GET response, I have Stackoveflow error
Controller for answer
@Controller
public class TaskViewController {
@Autowired
private TaskService taskService;
@RequestMapping(value = "/task/view", method = RequestMethod.GET)
public @ResponseBody
AjaxResponseBody getTask(@RequestParam String text) {
int id;
AjaxResponseBody result = new AjaxResponseBody();
Task task;
System.out.println(text);
try {
id = Integer.parseInt(text);
}
catch (Exception e) {
result.setMsg("Invalid task number");
return result;
}
task = taskService.findById(id);
if (task == null){
result.setMsg("Task not found");
return result;
}
result.setTask(task);
return result;
}
}
He uses class AjaxResponseBody for answer
public class AjaxResponseBody {
private String msg;
private Task task;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Task getTask() {
return task;
}
public void setTask(Task task) {
this.task = task;
}
}
and when this controller works I catch
2017-11-24 10:47:10.514 WARN 1448 --- [nio-8080-exec-4] .w.s.m.s.DefaultHandlerExceptionResolver : Failed to write HTTP message: org.springframework.http.converter.HttpMessageNotWritableException: Could not write content: Infinite recursion (StackOverflowError) (through reference chain: tracker.models.Project_$$_jvstd06_4["user"]->tracker.models.User_$$_jvstd06_5["watched_project"]->tracker.models.Project_$$_jvstd06_4["user"]->tracker.models.User_$$_jvstd06_5["watched_project"]->tracker.models.Project_$$_jvstd06_4["user"]->tracker.models.User_$$_jvstd06_5["watched_project"]->tracker.models.Project_$$_jvstd06_4["user"]->tracker.models.User_$$_jvstd06_5["watched_project"]->
How I understand this happens because model User and model Project has links to each other. Model User has an optional field "watched_project".
@Entity
@Table(name = "users")
public class User {
@ManyToOne(fetch = FetchType.LAZY)
private Project watched_project;
public Project getWatched_project() {
return watched_project;
}
public void setWatched_project(Project watched_project) {
this.watched_project = watched_project;
}
And model Project has field with not empry field "author":
@Entity
@Table(name = "projects")
public class Project {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private int id;
@Column(nullable = false)
@NotEmpty(message = "*Please provide project name")
private String projectName;
@ManyToOne(optional = false, fetch = FetchType.EAGER)
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
How I can abort itteration? Or any way?
Upvotes: 1
Views: 67
Reputation: 2276
JSON serialization tries to serialize object and you have circular reference. There are plenty questions in SO about it. If you are using Jackson then you can use annotation @JsonIgnore
for Project
object inside User
or User
object inside Project
.
Also you can use @JsonManagedReference
and @JsonBackReference
like in this answer.
Upvotes: 2