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 ;
}
异常
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
,其中存在关联性和lazyinitialization异常的可能性,但我仍然得到上述异常。我不知道我错过了什么。
答案 0 :(得分:5)
尝试将@JsonIgnore
放在getter而不是字段上,例如
@JsonIgnore
public List<Cart> getCarts() {...}
答案 1 :(得分:1)
在这种情况下,您有两种解决方法:
1-急切地抓住所有关系:
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
2-在延迟加载中,只需将DBO对象转换为另一个bean并在响应时返回它。
据我所知,@ JsonIgnore是一个方法注释,试着把它放在getter上,就像@Predrag Maric提到的那样
答案 2 :(得分:1)
JsonIgnore有两个版本。
com.fasterxml.jackson.annotation.JsonIgnore
和
org.codehaus.jackson.annotate.JsonIgnore
第一个是对的。