春天递归关联得到重复"孩子

时间:2017-10-23 11:45:24

标签: java recursion spring-data

我使用spring mongodb进行实体PimEntity的递归关联 这是我的文件: PimEntityDefinition.java

abstract class PimEntityDefinition {
    @Id
    private String id;
    private String code;
    private String type;

    public PimEntityDefinition() {
    }

PimEntity.java

public class PimEntity extends PimEntityDefinition {
    @DBRef(lazy = true)
    private List<PimEntity> subEntities;
    @DBRef(lazy = true)
    private List<PimAttribute> attributes;

当我调用findAll函数时 this.entitiesRepository.findAll();

我得到:

[
 {
        "id": "59ed96e4e4b014bdcd2fcc8f",
        "code": "tree1",
        "type": "tree",
        "subEntities": [
            {
                "id": "59ed9702e4b014bdcd2fcc90",
                "code": "tree1.1",
                "type": "tree",
                "subEntities": [],
                "attributes": null
            }
        ],
        "attributes": null
    },
        {
                "id": "59ed9702e4b014bdcd2fcc90",
                "code": "tree1.1",
                "type": "tree",
                "subEntities": [],
                "attributes": null
    }]

我怎样才能获得&#34; 59ed9702e4b014bdcd2fcc90&#34;只有一次?

感谢您的帮助。

我添加了像@Noixes建议的父属性,但我有一个无限循环 有或没有懒惰的参数。

public class PimEntity extends PimEntityDefinition {
    @DBRef(lazy = true)
    private List<PimEntity> parents;
    @DBRef(lazy = true)
    private List<PimEntity> subEntities;
    @DBRef(lazy = true)
    private List<PimAttribute> attributes;

getAll给出:

[ {
  "id" : "59edea6ce4b0df77770c7374",
  "code" : "tree1",
  "type" : "tree",
  "parents" : [ ],
  "subEntities" : [ {
    "id" : "59edea8de4b0df77770c7375",
    "code" : "tree1.1",
    "type" : "tree",
    "parents" : [ {
      "id" : "59edea6ce4b0df77770c7374",
      "code" : "tree1",
      "type" : "tree",
      "parents" : [ ],
      "subEntities" : [ {
        "id" : "59edea8de4b0df77770c7375",
        "code" : "tree1.1",
        "type" : "tree",
        "parents" : [ {
          "id" : "59edea6ce4b0df77770c7374",
          "code" : "tree1",
          "type" : "tree",
          "parents" : [ ],
          "subEntities" : [ {
            "id" : "59edea8de4b0df77770c7375",
            "code" : "tree1.1",
            "type" : "tree",
            "parents" : [ {
              "id" : "59edea6ce4b0df77770c7374",
                ...

@DBRef(lazy = true)private List parent不工作?

1 个答案:

答案 0 :(得分:0)

由于您的数据结构表明没有根元素,您可以获得这些结果。第一个实体包含secound,因为您将它添加到第一个实体。获取secound因为它也是此类的实体。但是它里面没有任何实体。 也许你应该改变你的数据结构,使除了根元素之外的所有元素都有一个父实体。 您还希望实现自己的fetchAll函数,在该函数中指定要获取的根元素。 您还可以创建一个查询,询问包含子实体的元素。