首页 > 解决方案 > Spring Data Neo4j 6 @ConvertWith 实现

问题描述

我正在尝试@ConvertWith在列表属性上实现 neo4j。

@ConvertWith(converter = "SomeConverter.class") 
List<CustomObject> customObject;

我看到 SomeConverter 应该 impl ->

implements Neo4jPersistentPropertyConverter<List<CustomObject>>

但我无法让转换工作.. 它似乎总是要求在 CustomObject 中提供所需的 id 属性

java.lang.IllegalStateException: Required identifier property not found for class

它甚至可能不会进入我的转换器?

问题:为对象列表实现转换器的正确方法是什么?

标签: spring-bootneo4jspring-data-neo4j

解决方案


通过注册 GenericConverter 解决它而不使用 @ConvertWith 确实有效。所以你为实际的 MyCustomClass 编写一个转换器,到 neo4j 驱动程序 StringValue,而不是为整个列表(List)编写一个转换。因为 neo4j 可以从 List 中自行转换。然后不需要在属性上方写@ConvertWith 或其他任何东西,但下面的内容。

那么解决方案:

public class CustomConverter implements GenericConverter 

{
    @Override
    public Object convert(final Object source, final TypeDescriptor sourceType, final TypeDescriptor targetType)
    {
        if (sourceType.getType().equals(StringValue.class))
        {
            System.out.println("reading converted");
            return this.toEntityAttribute((StringValue) source);
        }
        else
        {
            System.out.println("writing converting");
            return this.toGraphProperty((MyCustomClass) source);
        }
    }

    @Override
    public Set<ConvertiblePair> getConvertibleTypes()
    {
        Set<ConvertiblePair> convertiblePairs = new HashSet<>();
        convertiblePairs.add(new ConvertiblePair(MyCustomClass.class, Value.class));
        convertiblePairs.add(new ConvertiblePair(Value.class, MyCustomClass.class));
        return convertiblePairs;
    }

    private MyCustomClass toEntityAttribute(final StringValue value)
    {
        MyCustomClass result = null;
        try
        {
            result = AbstractJsonConverter.createObjectFromJson(value.asString(), MyCustomClass.class);
        }
        catch (IOException e)
        {
            CustomConverter.log.warn(e.getMessage(), e);
        }
        System.out.println("reading result:" + result);
        return result;
    }

    private Value toGraphProperty(final MyCustomClass value)
    {
        String result = null;
        try
        {
            result = AbstractJsonConverter.createJsonFromObject(value);
        }
        catch (RepresenationCreationException e)
        {
            CustomConverter.log.warn(e.getMessage(), e);
        }
        return Values.value(result);
    }
}

然后你必须通过定义一个bean来注册转换器。

@Bean
public Neo4jConversions neo4jConversions()
{
    Set<GenericConverter> additionalConverters = Collections.singleton(new CustomConverter());
    return new Neo4jConversions(additionalConverters);
}

推荐阅读