got error after consuming rest service without @JsonIgnore

Viewed 1572

I have this mapping User *-----------1 Sexe

User.class

public class User {
    @ManyToOne
    @JoinColumn(name="sexe_id")
    private Sexe sexe;

   // Rest of the Attributes
}

Sexe.class

public class Sexe {    
    @OneToMany(mappedBy="sexe", fetch = FetchType.LAZY)
    private List<User> users;

   // Rest of the Attributes

}

and the controller for rest call

@GetMapping("/users")
public List<User> getAllUsers()
{
     System.out.println("Get all Users...");
     List<User> users = new ArrayList<>();
     userRepository.findAll().forEach(users::add);
     return users;
}

after using postman, I got this exception:

 at
 com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:719)
 ~[jackson-databind-2.9.6.jar:2.9.6]    at
 com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:155)
 ~[jackson-databind-2.9.6.jar:2.9.6]    at
 com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:727)
 ~[jackson-databind-2.9.6.jar:2.9.6]    at
 com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:719)
 ~[jackson-databind-2.9.6.jar:2.9.6]    at
 com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:155)
 ~[jackson-databind-2.9.6.jar:2.9.6]    at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serializeContents(CollectionSerializer.java:145)
 ~[jackson-databind-2.9.6.jar:2.9.6]    at
 com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serialize(CollectionSerializer.java:107)
 ~[jackson-databind-2.9.6.jar:2.9.6]    at
 com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serialize(CollectionSerializer.java:25)
 ~[jackson-databind-2.9.6.jar:2.9.6]    at
 com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:727)
 ~[jackson-databind-2.9.6.jar:2.9.6]    at
 com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:719)
 ~[jackson-databind-2.9.6.jar:2.9.6]    at
 com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:155)
 ~[jackson-databind-2.9.6.jar:2.9.6]    at

After googling, I found that the solution is to use @JsonIgnore. And this annotation resolves my problem. But the use of this annotation cause problems with angular.

Have you please any other proposition to avoid this exception ?. Thanks a lot for your help.

1 Answers
Related