如何在 Spring 模型中定义使用 Neo4j 嵌入对象

问题描述 投票:0回答:1

我会将以下结构存储在 Neo4J 数据库中,该数据库具有嵌入式对象owMe 和 sellFor 属于 Payment 类。

{
  "id":"id23",
  "oweMe": {
    "cost": 23
    "currency":"USD"
  }
  "soldFor": {
    "cost": 34
    "currency":"EUR"
  }
}

在 Spring Boot 中,我可以在 H2 数据库上将 @embedded 和 @Embeddable 注释与 JPArespository 一起使用,并且效果完美。

我想重复这个结构,但将其存储在 Neo4J 数据库中。由于 Neo4j 不支持 JPARepositry,我无法使用这些注释,但是我看到它根据参考资料使用 @NodeEntity 和 @Property/@Properties 来实现相同的结果。

参考文档显示了一个如下所示的示例,其中地址作为嵌入对象属性的前缀。

address.street=Downing Street
address.number=10

谢谢大家的帮助,

但是,当我运行该应用程序时,我收到一条错误消息,指出

"Required identifier property not found for class ... Payment"
并引用了嵌入的对象。虽然嵌入对象确实没有 @Id,因为嵌入对象不是 List<> 并且没有 @Node/@NodeEntity 定义,但我预计应该不需要 id。

虽然我可以通过编写自定义 getter 和 setter 来序列化嵌入对象以便将其存储为 JSON 字符串来克服这个问题,但这已经变得难以承受。

正如我期望这种嵌入总是完成的那样,有人可以给我指出一个我可以使用的示例吗?

spring neo4j spring-data-neo4j embeddable
1个回答
0
投票

Neo4j 不支持嵌入对象。这就是为什么除了使用

@CompositeProperty
和自定义转换器来“嵌入”您的对象之外没有其他方法。

例如,对于

soldFor
,其属性定义为:

@CompositeProperty(prefix="soldFor", converter = SoldForConverter.class)
private SoldFor soldFor;

还有像

这样的转换器
class SoldForConverter implements Neo4jPersistentPropertyToMapConverter<String, SoldFor> {

    @NonNull @Override
    public Map<String, Value> decompose(@Nullable SoldFor property, Neo4jConversionService conversionService) {

        final HashMap<String, Value> decomposed = new HashMap<>();
        if (property == null) {
            decomposed.put("cost", Values.NULL);
            decomposed.put("currency", Values.NULL);
        } else {
            decomposed.put("cost", Values.value(property.getCost()));
            decomposed.put("currency", Values.value(property.getCurrency()));
        }
        return decomposed;
    }

    @Override
    public SoldFor compose(Map<String, Value> source, Neo4jConversionService conversionService) {
        return source.isEmpty() ?
                null :
                new SoldFor(source.get("cost").asInt(), source.get("currency").asString());
    }
}

你将会得到

soldFor.cost=34
soldFor.currency="EUR"

示例取自

转换器:https://github.com/spring-projects/spring-data-neo4j/blob/c5d3458217124e1867f12bc47454eab85551c72b/src/test/java/org/springframework/data/neo4j/integration/shared/conversion/ThingWithCompositeProperties.java# L235

属性定义:https://github.com/spring-projects/spring-data-neo4j/blob/c5d3458217124e1867f12bc47454eab85551c72b/src/test/java/org/springframework/data/neo4j/integration/shared/conversion/RelationshipWithCompositeProperties.java #L44 并简化。

© www.soinside.com 2019 - 2024. All rights reserved.