无法写入 JSON:延迟初始化角色集合失败。当我删除 @JsonManagedReference 和 @JsonBackReference 它工作

Could not write JSON: failed to lazily initialize a collection of role. When I remove @JsonManagedReference and @JsonBackReference it works

我在获取类型时遇到错误,我不知道如何解决!我尝试用类似的问题解决方案来解决,但没有奏效。使用 java 11,Spring 启动 2.6.5,gradle

菜单控制器:

package com.magsad.msnav.controller;

import com.magsad.msnav.entity.Menu;
import com.magsad.msnav.service.MenuService;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import lombok.experimental.FieldDefaults;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@RestController
@RequestMapping("menu")
@RequiredArgsConstructor
@FieldDefaults(makeFinal = true,level = AccessLevel.PRIVATE)
public class MenuController {
    MenuService menuService;

    @GetMapping
    public List<Menu> getAllNodes(){
        return menuService.getAll();
    }

    @GetMapping("{nodeId}")
    public Menu getNodeById(@PathVariable Long nodeId){
        return menuService.getById(nodeId);
    }

    @GetMapping("query")
    public Menu getNodeByIdQuery(@RequestParam Long nodeId){
        return menuService.getById(nodeId);
    }

    @PostMapping
    public Menu create(@RequestBody Menu menu){
        return menuService.create(menu);
    }

    @PutMapping
    public Menu update(@RequestBody Menu menu){
        return menuService.update(menu);
    }

    @DeleteMapping("{id}")
    public void delete(@PathVariable Long nodeId){
        menuService.delete(nodeId);
    }
}

菜单实体

import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import lombok.*;

import javax.persistence.*;
import java.util.List;
import java.util.Set;


@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Menu implements Serializable {

    private static final long serialVersionUID = 1L;


    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(name = "url", nullable = false)
    private String url;

    @Column(name = "name")
    private String name;

    @JsonManagedReference
    @OneToMany(mappedBy="parent")
    private Set<Menu> children = new HashSet<>();

    @ManyToOne
    @JsonBackReference
    private Menu parent;
}

当我删除 @JsonManagedReference 和 @JsonBackReference 并将 @JsonIgnore 添加到 private Set

children = new HashSet<>() 时它起作用了。

//    @JsonManagedReference
    @OneToMany(mappedBy="parent")
    @JsonIgnore
    private Set<Menu> children = new HashSet<>();

    @ManyToOne
//    @JsonBackReference
    private Menu parent;

菜单存储库

import com.magsad.msnav.entity.Menu;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface MenuRepository extends JpaRepository<Menu,Long> {
}

菜单服务

import com.magsad.msnav.entity.Menu;
import com.magsad.msnav.repository.MenuRepository;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import lombok.experimental.FieldDefaults;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@RequiredArgsConstructor
@FieldDefaults(makeFinal = true,level = AccessLevel.PRIVATE)
@Transactional
public class MenuService {
    MenuRepository menuRepository;

    public List<Menu> getAll() {
        return menuRepository.findAll();
/*                .stream()
                .filter(menu-> Objects.isNull(menu.getParent()))
                .collect(Collectors.toList());*/
    }

    public Menu getById(Long nodeId){
        return menuRepository.findById(nodeId).get();
    }

    public Menu create(Menu menu){
        return menuRepository.save(menu);
    }

    public Menu update(Menu menu){
        Menu menuForUpdate = menuRepository.findById(menu.getId()).get();
        menuForUpdate.setId(menu.getId());
        menuForUpdate.setName(menu.getName());
        menuForUpdate.setUrl(menu.getUrl());
        return menuRepository.save(menuForUpdate);
    }

    public void delete(Long nodeId) {
        menuRepository.deleteById(nodeId);
    }

}

我多次尝试类似的问题解决方案,但都没有解决。

entityGraph,Eager Lazy,配置

https://www.netsurfingzone.com/hibernate/failed-to-lazily-initialize-a-collection-of-role-could-not-initialize-proxy-no-session/

https://github.com/FasterXML/jackson-core/issues/469

创建 Json 对象时,如果您没有在 relationship attribut 上指定 @JsonIgnore and/or @JsonBackReference 属性。这样做是为了让一个 对象不会一遍又一遍地生成另一个 ,它很容易变成一个 无限循环 而你永远不会得到response 到您的查询。
@JsonIgnore 告诉 jpa 不要将子列表放入 Json 以阻止无限循环的发生。

我刚刚删除了 @Data 注释,而不是我写了 @Getter @Setter @ToString @EqualsAndHashCode,添加了 @OneToMany(mappedBy = "parent",fetch = FetchType.EAGER) 并且工作了!