Spring Data Neo4j 4 - How to implement Composite Attribute at Class?

五迷三道 提交于 2019-12-08 06:09:07

问题


I am looking for Composite Attribute example but can not find it everywhere. I have simple class :

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

MyClass have property diameter, it should be value from inDiameter or outDiameter (can use both as value with some condition)

And I have the other class like this:

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

How I can achieve that?

Do I need to create class for dummy diameter like this?

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

And I change my property of MyClass :

Double diameter -> NominalDiameter diameter;

I'm using Spring boot parent 1.4.1.RELEASE, neo4j-ogm 2.0.5, Spring Data Neo4j 4


回答1:


In the latest version of OGM - 2.1.0-SNAPSHOT there is a @CompositeAttributeConverter that can be used for this purpose.

Example of mapping multiple node entity properties onto a single instance of a type:

/**
* 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;
    }

}

To use:

@NodeEntity
public class Person {

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

To depend on this version:

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


来源:https://stackoverflow.com/questions/40215170/spring-data-neo4j-4-how-to-implement-composite-attribute-at-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!