2

在我的@RelationshipEntity下面,你可以看到我有一个Set<Right> rights(一组权利)。Right是一个Emum。Neo4J 只允许我保存一组String',所以我创建了一个自定义转换器。

@RelationshipEntity (type="LOGIN")
public class Login {

    @GraphId
    Long id;

    @StartNode
    Person person;

    @EndNode
    Organisation organisation;

    @Property
    String role;

    @Property
    @Convert(RightConverter.class)
    Set<Right> rights = new HashSet<Right>();

    public Login() {
        // Empty Constructor
    }

    /* Getters and Setters */

}

这对我来说很有意义,但是当我运行应用程序时,我的RightConverter班级出现错误。

public class RightConverter implements AttributeConverter<Set<Right>, Set<String>> {
    public Set<String> toGraphProperty(Set<Right>  rights) {
        Set<String> result = new HashSet<>();
        for (Right right : rights) {
            result.add(right.name());
        }
        return result;
    }

    public Set<Right> toEntityAttribute(Set<String> rights) {
        Set<Right> result = new HashSet<>();
        for (String right : rights) {
            result.add(Right.valueOf(right));
        }
        return result;
    }
}

它适用于保存,但不适用于加载:

nested exception is org.neo4j.ogm.metadata.MappingException: Error mapping GraphModel to instance of com.noxgroup.nitro.domain.Person
Caused by: java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.util.Set
at com.noxgroup.nitro.domain.converters.RightConverter.toEntityAttribute(RightConverter.java:9) ~[main/:na]
4

1 回答 1

2

如果您使用的是 SDN 4 的最新快照(即发布 M1 版本),则无需为枚举集合或数组编写转换器。默认枚举转换器将为您将枚举集转换为字符串数组。

但是,如果您使用的是较早的版本(M1),则不存在此支持,因此您确实需要编写转换器。在这种情况下,RightConverter只需更改为转换为 Neo4j 最终将使用的字符串数组,而不是集合。这有效:

public class RightConverter implements AttributeConverter<Set<Right>, String[]> {
    public String[] toGraphProperty(Set<Right>  rights) {
        String[] result = new String[rights.size()];
        int i = 0;
        for (Right right : rights) {
            result[i++] = right.name();
        }
        return result;
    }

    public Set<Right> toEntityAttribute(String[] rights) {
        Set<Right> result = new HashSet<>();
        for (String right : rights) {
            result.add(Right.valueOf(right));
        }
        return result;
    }
}
于 2015-05-30T16:29:21.947 回答