自我引用与spring数据jpa的关系

问题描述 投票:0回答:1

我正在使用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 */

}

department controller.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

我在这做错了什么?

json spring-boot spring-data-jpa objectmapper self-reference
1个回答
1
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.