弹簧数据jpa的自引用关系

时间:2019-03-06 14:50:40

标签: json spring-boot spring-data-jpa objectmapper self-reference

我正在使用Spring Boot构建应用程序,并且必须设置自引用关系。

为了使场景简单易懂,我尝试使用部门实体示例来处理类似场景。

以下是我需要建立自引用关系的情况

  1. 创建具有以下属性的部门-名称,成本中心,位置。
  2. 部门可以与父部门相关,该部门也是部门类型
  3. 部门可以具有子部门(子部门),也属于部门类型。

要设置这种情况,我已通过以下方式定义了实体部门。

Department.java

public class Department {

    @Id
    @GenericGenerator(name = "sequence_department_id", strategy = "com.app.mycompany.AgileCenterServices.util.DepartmentIdGenerator")
    @GeneratedValue(generator = "sequence_department_id")
    @Column(unique = true)
    private String id;

    private String name;

    private String location;

    private String costCenter;

    @ManyToOne(cascade=CascadeType.ALL)
    @JoinColumn(name="parentDepartment")
    private Department parentDepartment;

    @OneToMany(mappedBy="parentDepartment")
    private Set<Department> linkedDepartments = new HashSet<Department>();

    /* getters & setters */

}

DepartmentController.java

@CrossOrigin
    @RequestMapping(value = "/", method = RequestMethod.POST)
    public Department createDepartment(@RequestBody String trial) throws Exception {

        logger.info("Inside createDepartment() API ");

        ObjectMapper objmapper = new ObjectMapper();

        ObjectNode node = objmapper.readValue(trial, ObjectNode.class);

        Department deptInput = objmapper.convertValue(node, Department.class);

        Department deptRec = null;

        /* check if parent department information was passed */
        if(deptInput.getParentDepartment() != null) {
            Department parentDepartment = departmentRepository.findOne(deptInput.getParentDepartment().getId());
            deptInput.setParentDepartment(parentDepartment);

        }

        try {

            logger.info("createDepartment() :: Before save :: Input data ::: " + deptInput.toString());

            deptRec = departmentRepository.save(deptInput);

            logger.info("createDepartment() :: After save :: Saved successfully ::: " + deptRec.toString());
        } 
        catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }

        logger.info("Leaving createDepartment() API");

        return deptRec;
    }

就目前而言,我刚刚尝试将部门链接到上例所示的另一个parentDepartment,并尝试使用spring boot-REST服务创建部门

正在适当地创建部门。

Saved Department 1 with following input
{"name":"Sales", "costCenter": "SLS", "location":"Global"}
Output:
{
    "id": "1000",
    "name": "Sales",
    "location": "Global",
    "costCenter": "SLS",
    "parentDepartment": null,
    "linkedDepartments": []
}

    Saved department 2 with following input
    {"name":"Sales-IN", "costCenter": "SLS-IN", "location":"India", "parentDepartment":{"id":"1000"}}

  Output:   
    {
        "id": "1001",
        "name": "Sales-IN",
        "location": "India",
        "costCenter": "SLS-IN",
        "parentDepartment": {
            "id": "1000",
            "name": "Sales",
            "location": "Global",
            "costCenter": "SLS",
            "parentDepartment": null,
            "linkedDepartments": []
        },
        "linkedDepartments": []
    }

但是,当我现在使用邮递员查询部门中的数据时,我注意到以下异常

@CrossOrigin
    @RequestMapping(value="/", method = RequestMethod.GET)
    public Page<Department> listDepartments(Pageable pageable) {

        logger.info("Inside listDepartments() API");

        return departmentRepository.findAll(pageable);
    }

例外

2019-03-06 20:04:12.190  WARN 19520 --- [io-8080-exec-10] .m.m.a.ExceptionHandlerExceptionResolver : Resolved exception caused by handler execution: org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: Infinite recursion (StackOverflowError); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion (StackOverflowError) (through reference chain: com.app.mycompany.AgileCenterServices.entities.Department["linkedDepartments"]->org.hibernate.collection.internal.PersistentSet[0]->com.app.mycompany.AgileCenterServices.entities.Department["parentDepartment"]->com.app.mycompany.AgileCenterServices.entities.Department["linkedDepartments"]->org.hibernate.collection.internal.PersistentSet[0]->com.app.mycompany.AgileCenterServices.entities.Department["parentDepartment"]->com.app.mycompany.AgileCenterServices.entities.Department["linkedDepartments"]

要解决上述问题,我在“ linkedDepartments”属性上设置了@JsonBackReference,之后“ GET”操作可以正常工作。但是保存操作现在失败,并显示

2019-03-06 20:19:03.176  WARN 19520 --- [nio-8080-exec-3] .m.m.a.ExceptionHandlerExceptionResolver : Resolved exception caused by handler execution: org.springframework.web.util.NestedServletException: Handler dispatch failed; nested exception is java.lang.StackOverflowError

我在这里做什么错了?

1 个答案:

答案 0 :(得分:1)

我尝试了您的代码,只要您在linkedDepartments或parentDepartment上具有@JsonBackReference,它就不会被序列化,从而解决了无限递归问题。保存方法也可以正常工作。我可以将代码发布到GitHub供您参考。让我知道。