[英]Could not write JSON: failed to lazily initialize a collection of role one to one
我有以下代码......这是一个用户有一堵墙的应用程序,在那堵墙上可以有几个游戏。
@Entity
@Table(name = "tb_user")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToOne(mappedBy = "user",fetch = FetchType.EAGER)
private Mural mural;
public User() {
}
public User(Long id, String name, Mural mural) {
this.id = id;
this.name = name;
this.mural = mural;
//getters and setters...
}
@Entity
@Table(name = "tb_mural")
public class Mural implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@ManyToMany
@JoinTable(name = "tb_mural_games",
joinColumns = @JoinColumn(name = "mural_id"),
inverseJoinColumns = @JoinColumn(name = "games_id"))
private Set<Game> games = new HashSet<>();
@OneToOne
@JoinColumn(name = "user_id")
private User user;
public Mural() {
}
public Mural(Long id, String name, User user) {
this.id = id;
this.name = name;
this.user = user;
}
//getters and setters...
以下请求...
@GetMapping
public ResponseEntity<List<User>> findAll(){
List<User> list = repository.findAll();
return ResponseEntity.ok().body(list);
}
但我有以下错误...
Resolved [org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: failed to lazily initialize a collection of role... continue...
我尝试使用 FETCH.EAGER 但它不起作用,它只有在我使用 jsonignore 时才有效,但我希望它在用户请求中返回“壁画”。
将 JsonIgnore 放在壁画 class 上
@OneToOne
@JoinColumn(name = "user_id")
private User user;
还要尽量避免直接将实体返回给最终用户。 尝试将实体 map 转换为 DTO 或使用投影( https://docs.spring.io/spring-data#/jpa/docs/current/referenceshtml )。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.