how to Fix spring boot one to many bidirectional infinity loop?

后端 未结 3 1354
被撕碎了的回忆
被撕碎了的回忆 2021-01-20 00:45

i am try to create a one to many bidirectional mapping using spring boot and spring data jpa please look the below entity

Employer Entity

相关标签:
3条回答
  • 2021-01-20 00:59

    You can solve your issue with two modification with annotations.
    Employer.class

    @Entity
    public class Employer {
        private Long id;
        private String employerName;
    
        @OneToMany(cascade = CascadeType.ALL,
                mappedBy = "employer",
                orphanRemoval = true)
        private List<Employee> employees;
    
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        public Long getId() {
            return id;
        }
    
        public void setId(Long id) {
            this.id = id;
        }
    
        public String getEmployerName() {
            return employerName;
        }
    
        public void setEmployerName(String employerName) {
            this.employerName = employerName;
        }
    
        public List<Employee> getEmployees() {
            return employees;
        }
    
        public void setEmployees(List<Employee> employees) {
            this.employees = employees;
        }
    }
    


    Employee.class

    @Entity
    public class Employee {
        private Long id;
        private String employeeName;
    
    
        @ManyToOne(fetch = FetchType.LAZY)
        @JoinColumn(name = "employer_id")
        private Employer employer;
    
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        public Long getId() {
            return id;
        }
    
        public void setId(Long id) {
            this.id = id;
        }
    
        public String getEmployeeName() {
            return employeeName;
        }
    
        public void setEmployeeName(String employeeName) {
            this.employeeName = employeeName;
        }
    
        public Employer getEmployer() {
            return employer;
        }
    
        public void setEmployer(Employer employer) {
            this.employer = employer;
        }
    }
    

    For more information please visit this link.

    0 讨论(0)
  • 2021-01-20 01:01

    with the JSON its a problem with bi-directional mapping. Use the below properties.

    @JsonIgnoreProperties("employer")
    @JsonIgnoreProperties("employees")
    

    please keep fetching type as eager.

    hope this will work.

    0 讨论(0)
  • 2021-01-20 01:17

    Instead of using @JsonBackReferenceand @JsonManagedReference try to use annotation @JsonIgnoreProperties:

    @JsonIgnoreProperties("employer")
    private List<Employee> employees;  
    
    @JsonIgnoreProperties("employees")
    private Employer employer;  
    

    It prevents Jackson from rendering a specified properties of associated objects.

    0 讨论(0)
提交回复
热议问题