Spring Boot JPA - OneToMany relationship causes infinite loop
Problem solved. I was using a custom @toString
method in the LinkedAccount which was referencing the ParentAccount. I had no idea that this could cause any problem and therefor I did not include the toString in my question.
Apparently, this was causing an infinite loop of lazy loading and removing this reference fixed the problem.
Hibernate @OneToMany Relationship Causes Infinite Loop Or Empty Entries in JSON Result
I ran into exactly the same problem. I tried the solution from the quoted paragraph, it did not work for me.
What I did is to return null for getMovie() in Clip class, then the infinite loop issue is gone. The data returned in JSON format will look like {"movieId":1 ... clips:["clipId":1, "movie":"null", ..]}.
If you also want further remove the movie property in JSON, add the class-level annotation to Clip class
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
Jackson feature: prevent serialization of nulls, default values
Update:
The easier way I found is to simply remove the getter of movie in Clip class.
Jpa entity relationship caused endless loop
This problem cause by the bidirectional relationships. you can use
@JsonManagedReference and @JsonBackReference
- @JsonManagedReference is the forward part of reference – the one that
gets serialized normally. - @JsonBackReference is the back part of reference – it will be omitted
from serialization.
in your case you can add @JsonManagedReference in User class
@OneToMany(cascade = CascadeType.ALL,mappedBy = "belongUser")
@JsonManagedReference
private Set<BizInformation> bizs = new HashSet<BizInformation>();
and @JsonBackReference for Biz class which will omit the UserInformation serialization
@ManyToOne(fetch=FetchType.LAZY,cascade = CascadeType.ALL)
@JoinColumn(name = "user_id")
@JsonBackReference
private UserInformation belongUser;//所属用户
you can also use @JsonIgnore for the class that you want to omit the serialization
more detail : jackson-bidirectional-relationships-and-infinite-recursion
Spring Data JPA @OneToMany infinite loop exception
I think I'm getting the point of your problem. You want to fetch MyUser
including the userGroup
data without the circular reference.
Based from the solutions you enumerated, I suggest you should still use the @JsonBackReference
and @JsonManagedReference
to prevent recursion on your entities and for the solution on your problem, you can try to use a mapper (MapStruck) and map the userGroup details to a DTO during the retrieval of data from the service.
DTOs:
public class MyUserDto {
private Long id;
private String firstName;
private String lastName;
private String email;
private Integer age;
private UserGroupDto userGroupDto;
}
public class UserGroupDto {
private Long id;
private Integer groupOrder;
}
Mapper (MapStruck):
@Mapper(componentModel = "spring")
public interface MyUserMapper {
MyUserMapper INSTANCE = Mappers.getMapper(MyUserMapper.class);
UserGroupDto userGroupToDto(UserGroup userGroup);
@Mapping(source = "myUser.userGroup", target = "userGroupDto")
MyUserDto myUserToDto(MyUser myUser);
}
After retrieving the data from your repository
, you may then call the myUserToDto
method to map the entity to a DTO.
This is just one way of solving your problem.
how to Fix spring boot one to many bidirectional infinity loop?
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.
Spring-boot JPA infinite loop many to many
Your controller shoud not return entities ( classes with the annotation @Entity). As a best practice is to create another separate class with same attributes. This code has a little dupplication but it keeps all the layers clean. I also suggest to use @Service.
public class RoomDTO {
private String name;
private List<TeamDTO> teams = new ArrayList<>();
public RoomDTO() {
}
public RoomDTO(Room room) {
this.name = room.name;
for(Team team : room.getTeams()) {
TeamDTO teamDTO = new TeamDTO();
teamDTO.setName(team.getName);
teams.add(teamDTO);
}
}
}
public class TeamDTO {
List<RoomDTO> rooms = new ArrayList();
public TeamDTO() {
}
public TeamDTO(Team team) {
this.name = team.name;
for(Room room : team.getRooms()) {
RoomDTO roomDTO = new RoomDTO();
roomDTO.setName(team.getName);
rooms.add(roomDTO);
}
}
}
The controller should return this
@GetMapping
public Iterable<TeamDTO> getAllRoomsOfTeam() {
final long exampleId = 1;
final var team = teamRepository.findById(exampleId);
TeamDTO teamDTO = new TeamDTO(team);
return ResponseEntity.ok(teamDTO);
}
How to use DTOs in the Controller, Service and Repository pattern
JPA result infinite loop when using @OneToMany
Use
@JsonManagedReference
annotation for the first objects instantiated
@JsonBackReference
annotation for the second objects instantiated
Related Topics
How to Get Image Height and Width Using Java
Correct Way to Implement Http Connection Pooling
How to Initialize a Byte Array in Java
Badpaddingexception Decrypting the Encrypted Data in Android
Removing a Column in Java from a 2D Array
In Activity.Oncreate(), Why Does Intent.Getextras() Sometimes Return Null
Spring Data Query Method With Optional @Param
Java Xmlbeans Throws Nosuchmethod Error
Why Is Git Bash Not Using the Correct Java Path as Defined in the Path Environment Variable
I Want to Execute Code Every X Seconds, But Handler.Postdelayed Not Working
Simple Export and Import of a Sqlite Database on Android
How to Extract Ip Address in Spring MVC Controller Get Call
Can a @Manytoone JPA Relation Be Null
Hibernate Error - Querysyntaxexception: Users Is Not Mapped [From Users]
How Find Given Number Is Octal or Not
Java.Lang.Noclassdeffounderror: Com/Fasterxml/Jackson/Databind/Exc/Invaliddefinitionexception