用户 Controller .java
@RequestMapping("/listusersjson")
public ResponseEntity<Iterable<User>> getListofUsersJson() {
Iterable<User> users = userService.listUser();
return new ResponseEntity<>(users, HttpStatus.OK);
}
用户.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 ;
}
异常
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"])
即使我在所有存在一对一关系和延迟初始化异常可能性的必填字段上添加了 @jsonignore
,但我仍然收到上述异常。我不知道我错过了什么.
最佳答案
尝试将 @JsonIgnore
放在 getters 而不是字段上,例如
@JsonIgnore
public List<Cart> getCarts() {...}
关于java - @jsonignore 在 spring mvc 中没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35452586/