sdsdsdsd fdfdfwwq
sdsdsdsd fdfdfwwq

Reputation: 57

getting the StackOverflowError in below piece of java code

I am trying to implement the soft delete on a table and below is the code I have done to achieve the same

@Entity
@Data
@Table(name = "users")
public class User implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String name;
    private String surname;

    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
    private List<Product> products = new ArrayList<>();

}

I am getting the below exception on debugging

Method threw 'java.lang.StackOverflowError' exception. Cannot evaluate com.test.User.toString()

please advise it is related to the impact of Lombok that I am using in the entity.

Upvotes: 3

Views: 3997

Answers (1)

Michał Krzywański
Michał Krzywański

Reputation: 16920

Lombok @Data generates toString for you and you are probably using bidirectional association in your Product class. And probably Product also has toString method overriden. You are simply getting infinite loop of toString calls because of this bidirectional association I guess.

One solution suggested by lealceldeiro would be to exclude products field in your User class from being taken into account for toString method generation. You can achieve this by annotating your field with @ToString.Exclude lombok annotation :

@ToString.Exclude
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
private List<Product> products = new ArrayList<>();

Or you could exclude the user field in your Product entity.

You can read about lombok @ToString on their official site.

Upvotes: 5

Related Questions