【问题标题】:Could not write JSON: failed to lazily initialize a collection of role one to one无法写入 JSON:未能一对一地延迟初始化角色集合
【发布时间】:2022-01-11 05:34:59
【问题描述】:

我有以下代码... 这是一个用户有一面墙的应用程序,而那面墙上可以有几个游戏。

@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 时才有效,但我希望它在用户请求中返回“壁画”。

用户请求数据是这些=

[
    {
        "id": 1,
        "name": "Anderson Conforto"
    },
    {
        "id": 2,
        "name": "Airton Conforto"
    }
]

但是使用jsonignore,它会忽略壁画类数据,这不是我想要的。

【问题讨论】:

    标签: java spring-boot hibernate spring-data-jpa one-to-one


    【解决方案1】:

    将JsonIgnore放在Mural类中

    @OneToOne
    @JoinColumn(name = "user_id")
    private User user;
    

    还要尽量避免将实体直接返回给最终用户。尝试将实体映射到 DTO 或使用投影 (https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#projections)。

    【讨论】:

    • 我在壁画类中使用了jsonignore,但同样的错误仍然存​​在,如果我在用户类中使用jsonignore它可以工作,但它不会带来壁画类的数据,只是id和姓名。用户请求 = [ { "id": 1, "name": "Anderson Conforto" }, { "id": 2, "name": "Airton Conforto" } ]
    • 我同意 ZeNitch 所说的。但是为了使您的代码正常工作,您可以尝试在 Controller 的 findAll() 方法上使用 @Transactional 注释。当 Lazy 初始化时,如果事务控制没有明确地交给 spring,会话通常会关闭。
    猜你喜欢
    • 2022-01-05
    • 2018-06-15
    • 1970-01-01
    • 1970-01-01
    • 2015-05-03
    • 2019-08-06
    • 2017-08-16
    • 1970-01-01
    • 2011-04-27
    相关资源
    最近更新 更多