spring-boot - 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
它甚至可能不会进入我的转换器?
问题:为对象列表实现转换器的正确方法是什么?
解决方案
通过注册 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);
}
推荐阅读
- node.js - “node server.js”工作,但“npm start”找不到节点
- mysql - 在ubuntu ec2实例中拒绝访问用户时如何重置root密码
- r - 仅当通过 javascript 生成 HTML 时,R 内联代码才在 RMarkdown 中执行
- java - 从电子邮件地址获取谷歌日历 ID
- django - 在可空字段中使用 Django 验证器
- swift - 如何用多个跨步的空格分隔字符串中的字符?
- r - 闪亮的如何刷新在服务器功能之前加载的数据
- python-3.x - 重新创建 WAV 文件
- tkinter - 如何在 tkinter 中将项目从一个列表框移动到另一个列表框
- html - 我想将导航项注册向右移动,我尝试了 ml-auto 和 justify-content-end 但它没有移动