質問

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.

役に立ちましたか?

解決

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;
            }
        }
    }
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top