StackOverflowError to String causes a circular reference

error contents

java.lang.StackOverflowError
	at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:675)
	at java.lang.StringBuilder.append(StringBuilder.java:208)
	at java.time.LocalDate.toString(LocalDate.java:2032)
	at java.lang.String.valueOf(String.java:2994)
	at java.lang.StringBuilder.append(StringBuilder.java:131)
	at demo.model.User.toString(User.java:19)
...

Before correction

The relationship between User and UserDetail is a OneToOne two-way relationship.

User


@Entity
@Data
public class User {

	@OneToOne(mappedBy = "user", cascade = CascadeType.ALL)
	private UserDetail userDetail;

UserDetail



@Entity
@Data
public class UserDetail implements Serializable {

	@OneToOne
	@JoinColumn
	@MapsId
	private User user;

Cause of circulation

I forgot that adding @Data in Lombok will also add `` `@ Getter / @ Setter``` and @ToString. .. ..

Where is the circulation happening? .. When User.toString is executed, DetailUser.toString is executed, and User.toString is further called in it to start circulation.

How to solve

Avoid calling DetailUser when User.toString is executed

User


@Entity
@Data
public class User {

	@OneToOne(mappedBy = "user", cascade = CascadeType.ALL)
	@ToString.Exclude //★★★ Define fields to exclude from toString
	private UserDetail userDetail;

Recommended Posts

StackOverflowError to String causes a circular reference
Convert to a tag to URL string in Rails
[Android] How to convert a character string to resourceId
Code to escape a JSON string in Java
Convert a string to a character-by-character array with swift
I want to simply write a repeating string
[Ruby] How to generate a random alphabet string
[Java] How to erase a specific character from a character string
Ruby Regular Expression Extracts from a specific string to a string
I want to add a reference type column later
URL to String conversion
Convert a Java byte array to a string in hexadecimal notation
How to change a string in an array to a number in Ruby
[Java] How to convert a character string from String type to byte type
How to store a string from ArrayList to String in Java (Personal)
I tried to convert a string to a LocalDate type in Java