Spring Data Neo4j - relationship properties on complex type class members

扶醉桌前 提交于 2019-12-24 22:07:12

问题


I have a class annotated with @RelationshipEntity. This class contains of object defined by me with some integer values. Is it possible somehow to define that members of the nested object will be saved as properties on the relationship?

Justyna.


回答1:


Yes, but they should be converted to strings providing customized Spring converters. To avoid declaring a converter for each class you need to embed, you could extend a common interface (even an empty one, just to declare the converters). The converters must be declared in the SDN configuration file as follows:

<bean id="conversionService"
          class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <list>
                <bean class="..."/>
                <bean class="..."/>
            </list>
        </property>
</bean>

You should define two converters, one for converting objects to strings and the other for the opposite conversion from string to objects. For example, using Gson:

final class ToStringConverterFactory implements ConverterFactory<MyClass, String> {

    @Override
    public <T extends String> Converter<MyClass, T> getConverter(Class<T> type) {
        return new ToStringConverter(type);
    }

    private final class ToStringConverter<E extends MyClass, S extends String> implements Converter<E, S> {

        private Class<S> stringType;

        public ToStringConverter(Class<S> stringType) {
            this.stringType = stringType;
        }

        @Override
        public S convert(E source) {
            if (source != null) {
                return (S) new Gson().toJson(source);
            } else {
                return null;
            }
        }
    }
}

final class ToObjectConverterFactory implements ConverterFactory<String, MyClass> {

    @Override
    public <T extends MyClass> Converter<String, T> getConverter(Class<T> type) {
        return new ToObjectConverter(type);
    }

    private final class ToObjectConverter<S extends String, E extends MyClass> implements Converter<S, E> {

        private Class<E> objectType;

        public ToObjectConverter(Class<E> objectType) {
            this.objectType = objectType;
        }

        @Override
        public E convert(S source) {
            if (source != null) {
                return (E) new Gson().fromJson(source, objectType);
            } else {
                return null;
            }
        }
    }
}


来源:https://stackoverflow.com/questions/22813004/spring-data-neo4j-relationship-properties-on-complex-type-class-members

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