Spring Data Neo4j 4 - 如何在类中实现复合属性?

时间:2016-10-24 09:39:22

标签: spring spring-mvc neo4j spring-data-neo4j-4

我正在寻找复合属性示例,但无法在任何地方找到它。我有简单的课程:

@NodeEntity
public class MyClass{
@GraphId Long id;
Double diameter; 
//Property diameter should be from composite attribute (inDiameter and outDiameter)
}

MyClass有属性直径,它应该是inDiameter或outDiameter的值(可以在某些条件下同时使用值)

我还有这样的其他课程:

@NodeEntity
public class MyClass2{
@GraphId Long id;
String name; 
//Property name should be from composite attribute (firstName and lastName)
}

我如何实现这一目标?

我是否需要像这样为虚拟直径创建类?

//without @NodeEntity
Class NominalDiameter{
     Double outsideDiameter
     Double insideDiameter
}

我改变了MyClass的属性:

Double diameter -> NominalDiameter diameter;

我使用Spring boot parent 1.4.1.RELEASE,neo4j-ogm 2.0.5,Spring Data Neo4j 4

1 个答案:

答案 0 :(得分:3)

在最新版本的OGM - 2.1.0-SNAPSHOT中,有@CompositeAttributeConverter可用于此目的。

将多个节点实体属性映射到单个类型实例的示例:

/**
* This class maps latitude and longitude properties onto a Location  type that encapsulates both of these attributes.
*/
public class LocationConverter implements CompositeAttributeConverter<Location> {

    @Override
    public Map<String, ?> toGraphProperties(Location location) {
        Map<String, Double> properties = new HashMap<>();
        if (location != null)  {
            properties.put("latitude", location.getLatitude());
            properties.put("longitude", location.getLongitude());
        }
        return properties;
    }

    @Override
    public Location toEntityAttribute(Map<String, ?> map) {
        Double latitude = (Double) map.get("latitude");
        Double longitude = (Double) map.get("longitude");
        if (latitude != null && longitude != null) {
            return new Location(latitude, longitude);
        }
        return null;
    }

}

使用:

@NodeEntity
public class Person {

   @Convert(LocationConverter.class)
   private Location location;
   ...
}

依赖此版本:

repositories {
    mavenLocal()
    mavenCentral()
    maven { url "http://m2.neo4j.org/content/repositories/snapshots/" }
    maven { url "https://repo.spring.io/libs-snapshot" }
}