Не выводит список отпусков для каждого сотрудника

Моя проблема следующая:

Написать REST API (контроллер и сервис) для сотрудников. Методы: получение списка сотрудников, получение 1 сотрудника по Id, изменение сотрудника, удаление сотрудника.

Для маппинга выбора сотрудника по id вывести список его отпусков. У меня не получается этого сделать.

Класс Сотрудник:

@Entity
@Table(name = "employee")
public class Employee {

    @Id
    @SequenceGenerator(name = "empl_seq", sequenceName = "employee_id_seq",allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE ,generator = "empl_seq")
    @Getter
    private Long id;
    @Column
    private String lastName;
    @Column
    private String firstName;
    @Column
    private String middleName;
    @Column
    private LocalDate birthDate;
    @Column
    private String code;
    @Column
    private LocalDate startDate;
    @Column
    private String login;
    @Column
    private String password;

    @OneToMany(mappedBy = "employee",orphanRemoval = true,cascade = CascadeType.ALL)
    private List<Vacation> vacations;
}

Класс Отпуск:

@Entity
@Table(name = "vacation")
public class Vacation {

    @Id
    @SequenceGenerator(name = "vac_seq", sequenceName = "vacation_id_seq",allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "vac_seq")
    private Long id;
    @Column
    private LocalDate startDate;
    @Column
    private LocalDate endDate;
    @ManyToOne
    @JoinColumn(name = "employee_id")
    private Employee employee;
}

Сервис сотрудников:

@Service
public class EmployeeService {

    private EmployeeRepository employeeRepository;

    @Autowired
    public EmployeeService(EmployeeRepository employeeRepository) {
        this.employeeRepository = employeeRepository;
    }

    public List<Employee> getAllEmployee() {
        List<Employee> employeeList = employeeRepository.findAll();
        if (employeeList.size() > 0) {
            return employeeList;
        } else return new ArrayList<Employee>();
    }

    public Employee getEmployeeById(Long id) throws Exception {
        Optional<Employee> employee = employeeRepository.findById(id);
        if (employee.isPresent()) {
            return employee.get();
        } else {
            throw new Exception("User was not found");
        }
    }
}

И сам контроллер:

@RestController
@RequestMapping("/employees")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;


    @GetMapping
    public ResponseEntity<List<Employee>> getAllEmployees() {
        List<Employee> employeeList = employeeService.getAllEmployee();
        return new ResponseEntity<List<Employee>>(employeeList, new HttpHeaders(), HttpStatus.OK);
    }

    @GetMapping("/{id}")
    public ResponseEntity<Employee> findEmployeeById(@PathVariable("id") Long id) throws Exception {
        Employee employee = employeeService.getEmployeeById(id);
        Map<Employee, Vacation> employeeVacationMap ;

        return new ResponseEntity<Employee>(employee, new HttpHeaders(), HttpStatus.OK);
    }

Если я не использую список отпусков в классе сотрудника, то всё работает корректно. Но как только я использую

@OneToMany(mappedBy = "employee",orphanRemoval = true, cascade = CascadeType.ALL)
private List<Vacation> vacations;

у меня в Postman вылетает очень длинный файл с повторяющимися данными, который невозможно читать. а в идее пишет :

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.example.demo.entity.Vacation["employee"]->com.example.demo.entity.Employee["vacations"]->org.hibernate.collection.internal.PersistentBag[0]->com.example.demo.entity.Vacation["employee"]->org.hibernate.collection.internal.PersistentBag[0]->com.example.demo.entity.Vacation["employee"]->com.example.demo.entity.Employee["vacations"]->org.hibernate.collection.internal.PersistentBag[0]->com.examp>org.hibernate.collection.internal.PersistentBag[0]->com.example.demo.entity.Vacation["employee"]->com.example.demo.entity.Employee["vacations"]->org.hibernate.collection.internal.PersistentBag[0]->com.example.demo.entity.Vacation["employee"]->com.example.demo.entity.Employee["vacations"]->org.hibernate.collection.internal.PersistentBag[0]->com.example.demo.entity.Vacation["employee"]->com.example.demo.entity.Employee["vacations"]->org.hibernate.collection.internal.PersistentBag[0]->com.example.demo.entity.Vacation["employee"]->com.example.demo.entity.Employee["vacations"]->org.hibernate.collection.internal.PersistentBag[0]->com.example.demo.entity.Vacation["employee"]->com.example.demo.entity.Employee["vacations"]->org.hibernate.collection.internal.PersistentBag[0]->com.example.demo.entity.Vacation["employee"]->com.example.demo.entity.Employee["vacations"]->org.hibernate.collection.internal.PersistentBag[0]->com.example.demo.entity.Vacation["employee"]->com.example.demo.entity.Employee["vacations"]->org.hibernate.collection.internal.PersistentBag[0]->com.example.demo.entity.Vacation["employee"]->com.example.demo.entity.Employee["vacations"]->org.hibernate.collection.internal.PersistentBag[0]->com.example.demo.entity.Vacation["employee"]->com.example.demo.entity.Employee["vacations"]->org.hibernate.collection.internal.PersistentBag[0]->com.example.demo.entity.Vacation["employee"]->com.example.demo.entity.Employee["vacations"]->org.hibernate.collection.internal.PersistentBag[0]->com.example.demo.entity.Vacation["employee"]->com.example.demo.entity.Employee["vacations"]->org.hibernate.collection.internal.PersistentBag[0]->com.example.demo.entity.Vacation["employee"]->com.example.demo.entity.Employee["vacations"]->org.hibernate.collection.internal.PersistentBag[0]->com.example.demo.entity.Vacation["employee"]->com.example.demo.entity.Employee["vacations"]->org.hibernate.collection.internal.PersistentBag[0]->com.example.demo.entity.Vacation["employee"]->com.example.demo.entity.Employee["vacations"]->org.hibernate.collection.internal.PersistentBag[0]->com.example.demo.entity.Vacation["employee"]->com.example.demo.entity.Employee["vacations"]->org.hibernate.collection.internal.PersistentBag[0]->com.example.demo.entity.Vacation["employee"]->com.example.demo.entity.Employee["vacations"]->org.hibernate.collection.internal.PersistentBag[0]->com.example.demo.entity.Vacation["employee"]->com.example.demo.entity.Employee["vacations"]->org.hibernate.collection.internal.PersistentBag[0]->com.example.demo.entity.Vacation["employee"]->com.example.demo.entity.Employee["vacations"]->org.hibernate.collection.internal.PersistentBag[0]->com.example.demo.entity.Vacation["employee"]->com.example.demo.entity.Employee["vacations"]->org.hibernate.collection.internal.PersistentBag[0]->com.example.demo.entity.Vacation["employee"]->com.example.demo.entity.Employee["vacations"]->org.hibernate.collection.internal.PersistentBag[0]->com.example.demo.entity.Vacation["employee"]->com.example.demo.entity.Employee["vacations"]->org.hibernate.collection.internal.PersistentBag[0]->com.example.demo.entity.Vacation["employee"]->com.example.demo.entity.Employee["vacations"]->org.hibernate.collection.internal.PersistentBag[0]->com.example.demo.entity.Vacation["employee"]->com.example.demo.entity.Employee["vacations"]->org.hibernate.collection.internal.PersistentBag[0]->com.example.demo.entity.Vacation["employee"]->com.example.demo.entity.Employee["vacations"]->org.hibernate.collection.internal.PersistentBag[0]->com.example.demo.entity.Vacation["employee"]->com.example.demo.entity.Employee["vacations"]->org.hibernate.collection.internal.PersistentBag[0]->com.example.demo.entity.Vacation["employee"]->com.example.demo.entity.Employee["vacations"]->org.hibernate.collection.internal.PersistentBag[0]->com.example.demo.entity.Vacation["employee"])] with root cause

java.lang.StackOverflowError: null

как быть,господа?


Ответы (1 шт):

Автор решения: Kaira
 @JsonManagedReference
 @OneToMany(mappedBy = "employee",orphanRemoval = true,cascade = CascadeType.ALL)
 private List<Vacation> vacations;

 @JsonBackReference
 @ManyToOne
 @JoinColumn(name = "employee_id")
 private Employee employee;
→ Ссылка