简体   繁体   中英

not able to fetch data from the db when

截屏 I am getting an error when trying to fetch data from the database (the data exists in the db). I am able to perform the action when there is no data in the db. This is my entities:

@Table(name = "tbl_task")
public class Task {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long taskId;
private String title;
private String description;
private Status status;
@ManyToOne
@JoinColumn(name = "user_id")
private User assignee;
@OneToMany(mappedBy = "task", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Comment> comments;

and:

@Entity
@Table(name = "tbl_user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long userId;
private String name;
@Column(unique = true)
private String email;
private Active active;
private String password;
@OneToMany(mappedBy = "assignee", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Task> tasks;
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Comment> comments;

the error is:

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw 
exception [Request processing failed; nested exception is 
org.springframework.http.converter.HttpMessageNotWritableException: Could not write 
JSON: Infinite recursion (StackOverflowError); nested exception is 
com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion 
(StackOverflowError) (through reference chain: 
com.tasksmanagement.entity.Task["assignee"]- 
>com.tasksmanagement.entity.User["tasks"]- 
>org.hibernate.collection.internal.PersistentBag[0]

This is the method:

    public List<TaskResponse> getAllTasks() {
    List<Task> tasks = taskRepository.findAll();
    return 

tasks.stream().map(this::mapToTaskResponse).collect(Collectors.toList()); }

Any idea how to solve this?

Thanks

I added @JsonManagedReference in the User class (List tasks field) and added @JsonBackReference in the Task class (User asignee field) and it solved the issue

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM