saurabh
saurabh

Reputation: 247

@jsonignore not working as expected in spring mvc

usercontroller.java

@RequestMapping("/listusersjson")
    public ResponseEntity<Iterable<User>> getListofUsersJson() {
        Iterable<User>   users = userService.listUser(); 
        return new ResponseEntity<>(users, HttpStatus.OK);

    }

user.java

@Entity
public class User {

    @Id
    @GeneratedValue
    @Column(name="user_id")
    private Integer id;

    private String name;

    private String email;

    private String password;

    private int enabled;

    public User(Integer id) {
        super();
        this.id = id;
    }


    public User() {
        super();
    }

    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "user_role", joinColumns = { @JoinColumn(name = "user_id") }, inverseJoinColumns = {
            @JoinColumn(name = "role_id") })
    @JsonIgnore
    private List<Role> roless;

    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
    @JsonIgnore
    private List<Cart> carts ;


    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
    @JsonIgnore
    private List<OrderDetails> orderDetails ;

}

Exception

 HTTP Status 500 - Could not write JSON: failed to lazily initialize a collection of role: com.addtocart.dto.User.roless, could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]->com.addtocart.dto.User["roles"]); nested exception is org.codehaus.jackson.map.JsonMappingException: failed to lazily initialize a collection of role: com.addtocart.dto.User.roless, could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]->com.addtocart.dto.User["roles"])

Even though I have added the @jsonignore on all required fields where there is onetomany relationship and chances of lazyinitialization exception but still I am getting the above exception.I don't know what I am missing.

Upvotes: 2

Views: 6521

Answers (3)

Hamedz
Hamedz

Reputation: 726

There are two version of JsonIgnore.

com.fasterxml.jackson.annotation.JsonIgnore

and

org.codehaus.jackson.annotate.JsonIgnore

the first one is right.

Upvotes: 1

Sercan Ozdemir
Sercan Ozdemir

Reputation: 4692

In such a situation you have two work arounds:

1- Eagerly fetching all relations:

@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)

2- In lazy loading, just convert your DBO object to another bean and return it at response.

And @JsonIgnore is a method annotation as far as I know, try putting it on getters as @Predrag Maric mentioned

Upvotes: 1

Predrag Maric
Predrag Maric

Reputation: 24433

Try putting @JsonIgnore on the getters instead of fields, e.g.

@JsonIgnore
public List<Cart> getCarts() {...}

Upvotes: 10

Related Questions