Search code examples
eclipsespring-boothibernate

SpringBoot @OneToMany infinite loop with Lombok


My project using SpringBoot, it has bidirectional mapping @OneToMany

@Entity
@Table(name = "T_S")
@Getter
@Setter
@EqualsAndHashCode
@NoArgsConstructor
@AllArgsConstructor
@ToString
    public class S implements Serializable {
        @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.MERGE)
        @JoinColumn(name = "something", referencedColumnName = "A_ID", nullable = false, insertable = false, updatable = false)
        @OptimisticLock(excluded = false)
        private Set<A> act = new HashSet<>();
        ....something...
    }

    @Entity
    @Table(name = "T_A")
    @Getter
    @Setter
    @EqualsAndHashCode
    @NoArgsConstructor
    @AllArgsConstructor
    @ToString
    public class A{
        @ManyToOne(optional = true, fetch = FetchType.LAZY)
        @JoinColumn(name = "A_ID", insertable = false, updatable = false)
        private S sub;
    }
  

whe i get data from repository it make infinitive loop. How to fix it ?


Solution

  • Please use @ToString.Exclude on that attribute which makes an infinite loop.

    @Entity
    @Table(name = "T_S")
    @Getter
    @Setter
    @EqualsAndHashCode
    @NoArgsConstructor
    @AllArgsConstructor
    @ToString
    public class S implements Serializable {
        @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.MERGE)
        @JoinColumn(name = "something", referencedColumnName = "A_ID", nullable = false, insertable = false, updatable = false)
        @OptimisticLock(excluded = false)
        private Set<A> act = new HashSet<>();
            ....something...
    }
    
    
    
    @Entity
    @Table(name = "T_A")
    @Getter
    @Setter
    @EqualsAndHashCode
    @NoArgsConstructor
    @AllArgsConstructor
    @ToString
    public class A{
        @ToString.Exclude -----------------> here is the change
        @ManyToOne(optional = true, fetch = FetchType.LAZY)
        @JoinColumn(name = "A_ID", insertable = false, updatable = false)
        private S sub;
    }