Spring boot JSON return infinite nested objects

Viewed 1036

I have the following in my code:

CompanyEntity

@Entity
@Table(name = "company")
public class Company{
   @OneToMany(mappedBy = "company", cascade = CascadeType.ALL)
   @JsonUnwrapped
   private Set<User> users;
}

UserEntity

@Entity
@Table(name="user")
public class User{
    @ManyToOne(cascade = CascadeType.REFRESH)
    @JoinColumn(name="company_id")
    private Company company;
}

CompanyController

@GetMapping("/company")
public ResponseEntity<Object> getAllCompanies(){
    List<Company> allCompanies = companyService.findAll();
    return ResponseEntity.ok(allCompanies);

}

problem is when i call /company in the browser i am getting the users object including the company object. something like this

[
    {
        "id": 1,
        "name": "company",
        "users": [
            {
                "id": 14,
                "firstName": "Yamen",
                "lastName": "Nassif",
                "company": {
                    "id": 1,
                    "name": "company",
                    "users": [
                        {
                            "id": 14,
                            "firstName": "Yamen",
                            "lastName": "Nassif",
                            "company": {
                                "id": 1,
                                "name": "company",
                                "users": [

...

same goes when i getAllUsers companies and users are also exanding.

my database looks just fine.

and its endless and of course Stackoverflow error is in the console. How can i fix this ?

2 Answers

You have this error because of the infinite recursion.

Company has a link on User and User has a link on Company.

You have at least two options:

e.g.

@GetMapping("/company")
public ResponseEntity<Object> getAllCompanies() {
    List<Company> allCompanies = companyService.findAll();
    List<CompanyDto> allCompanyDtoList = convertToCompanyDtoList(allCompanies);
    return ResponseEntity.ok(allCompanyDtoList );
}

Personally, I'd prefer the second option, since returning Entities is NOT a good practice.

You can use @JsonIgnore annotation to prevent this type of behavior. This usually happens with bidirectional mapping within your entities. It is caused by infinite recursion.

@Entity
@Table(name="user")
public class User{
    @ManyToOne(cascade = CascadeType.REFRESH)
    @JoinColumn(name="company_id")
    @JsonIgnore
    private Company company;
}
Related