Neo4j OGM查找节点及其相关节点

时间:2018-08-29 09:58:00

标签: java neo4j spring-data-neo4j neo4j-ogm

我有一对多的关系(模型1-> N字段),我想找到所有带有其字段的模型。但是模型的字段是空对象。

@NodeEntity
public class Model {
    @Id
    private String id;
    private String name;

    @Relationship(type = "ModelField", direction = Relationship.OUTGOING)
    private List<Field> fields = new ArrayList<Field>();
}

@NodeEntity
public class Field {
    @Id
    private String id;
    private String name;
}

public interface ModelRepo extends Neo4jRepository<Model, String>{
}

public ModelRepo mr;

Iterable<Model> models = mr.findALl();

// the model's fields is empty

1 个答案:

答案 0 :(得分:0)

我只是根据您的正确代码重新构建了您的方案,并且效果很好。我认为通过填充您的数据,出现了问题。由于缺少这段代码,因此我无法指出具体原因。不过,为了帮助您,我概述了检索字段节点的步骤。

添加FieldRepo存储库:

public interface FieldRepo extends Neo4jRepository<Field, String> {    
}

填充场景:

Model model = new Model("modelId1", "Model1");

Field field = new Field("fieldId1", "Field1");
model.getFields().add(field);

Field field2 = new Field("fieldId2", "Field2");
model.getFields().add(field2);

modelRepo.save(model);
fieldRepo.save(field);
fieldRepo.save(field2);

获取您的信息:

Iterable<Model> resultModels = modelRepo.findAll();
for (Model resultModel : resultModels) {
  System.out.println("Model: " + resultModel.getId() + " " + resultModel.getName());
  for (Field resultField : resultModel.getFields()) {
    System.out.println("\tField: " + resultField.getId() + " " + resultField.getName());
  }
}

这将产生以下预期输出:

Model: modelId1 Model1
    Field: fieldId1 Field1
    Field: fieldId2 Field2

Result - graphical representation

我希望这些信息对您有所帮助。请随时询问任何不清楚的项目。