gpt4 book ai didi

java - stackoverflow 创建对象

转载 作者:行者123 更新时间:2023-11-30 02:18:50 25 4
gpt4 key购买 nike

当我创建 GET 响应时,出现 Stackoveflow 错误

应答 Controller

@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;
}
}

他使用 AjaxResponseBody 类作为答案

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;
}
}

当这个 Controller 工作时我发现

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"]->

我如何理解发生这种情况是因为模型用户和模型项目彼此具有链接。模型用户有一个可选字段“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;
}

并且模型项目具有非空字段“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;
}

如何中止迭代?或者有什么办法吗?

最佳答案

JSON 序列化尝试序列化对象,并且您有循环引用。 SO 中有很多关于它的问题。如果您使用 Jackson,那么您可以使用注释 @JsonIgnore对于 Project里面的物体UserUser里面的物体Project .

您也可以使用@JsonManagedReference@JsonBackReference就像 this回答。

关于java - stackoverflow 创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47470953/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com