当前位置: 动力学知识库 > 问答 > 编程问答 >

How to convert a Object with enum attribute in Spring Data MongoDB?

问题描述:

I have the following class that I want to save and query from MongoDB. I managed to set a custom convert that converts from InstanceType to String and String to InstanceType. InstanceType is a custom enum that will be stored in a different way!

@Document

public class Instance {

private String name;

private InstanceType type;

private List<Configuration> configurations;

private Map<String, String> properties;

}

MongoConfiguration class

@Bean

@Override

public CustomConversions customConversions() {

List<Converter<?, ?>> converters = new ArrayList<>();

converters.add(new InstanceTypeToStringConverter());

converters.add(new StringToInstanceTypeConverter());

return new CustomConversions(converters);

}

@Bean

@Override

public MappingMongoConverter mappingMongoConverter() throws Exception {

MongoMappingContext mappingContext = new MongoMappingContext();

DbRefResolver databaseResolver = new DefaultDbRefResolver(mongoFactory());

MappingMongoConverter mongoConverter = new MappingMongoConverter(databaseResolver, mappingContext);

mongoConverter.setCustomConversions(customConversions());

mongoConverter.afterPropertiesSet();

return mongoConverter;

}

The problem I'm having is that when I try to query the Instance object in MongoDB, Spring uses StringToInstanceType to convert "name" attribute. Why Spring is using this converter? This converter should not only be applied to "type" attribute?

This is the query I'm trying to execute:

public Instance getInstance(InstanceType type, String name) {

return mongoTemplate.findOne(Query.query(

Criteria.where("type").is(type)

.and("name").is(name)

), Instance.class, COLLECTION_INSTANCES);

}

Type attribute is converted using InstanceTypeToStringConverter (Thats OK because the source is InstanceType and target is String)

Name attribute is converted using StringToInstanceTypeConverter (It's wrong because the source is String and target is a String)

Because os this behavior, the query is returning NULL.

Let's say I have the follow object in MongoDB:

{"type": "user", "name": "Sandro"}

InstanceType.USER is converted to "user" (InstanceTypeToStringConverter).

"Sandro" is converted to null (StringToInstanceTypeConverter) because InstanceType.getInstanceType("Sandro") returns null.

In this case Spring will query mongo this way:

Where type = "user" and name = null

分享给朋友:
您可能感兴趣的文章:
随机阅读: