我有一个POJO。我想通过使用spring data mongodb添加一些额外的字段将它保存到mongoDB。为此,我创建了自定义转换器。但是这个自定义自定义转换器不是根据自定义转换器调用而不是保存。请帮帮我
这里是MongoDbConfiguration类:
@Configuration
@EnableMongoRepositories(basePackages = { "com.db.sample" })
@ComponentScan(basePackages = "com.db.sample")
public class MongoDbConfiguration extends AbstractMongoConfiguration {
@Override
protected String getDatabaseName() {
return "test";
}
@Override
public Mongo mongo() throws Exception {
return new MongoClient("127.0.0.1", 27017);
}
@Override
public CustomConversions customConversions() {
List<Converter<?, ?>> converterList = new ArrayList<Converter<?, ?>>();
converterList.add(new SampleEventWriterConverter());
return new CustomConversions(converterList);
}
@Override
public String getMappingBasePackage() {
return "com.db.sample";
}
@Bean
public MongoTemplate mongoTemplate() throws Exception {
MongoTemplate mongoTemplate = new MongoTemplate(mongo(), "test");
MappingMongoConverter mongoMapping = (MappingMongoConverter) mongoTemplate.getConverter();
mongoMapping.setCustomConversions(customConversions());
mongoMapping.afterPropertiesSet();
return mongoTemplate;
}
}
这里是SampleEventWriterConverter类:
@Component
public class SampleEventWriterConverter implements Converter<SampleEvent, Document> {
@Override
public Document convert(SampleEvent event) {
Document doc = new Document();
doc.put("_id", event.getId());
// …
doc.put("sample", "test");
for (Map.Entry<String, Object> entry : event.getFields().entrySet()) {
doc.put(entry.getKey(), entry.getValue());
}
return doc;
}
}
此处存储库类:
@Repository
public interface SampleEventRepository extends MongoRepository<SampleEvent, ObjectId> {
}
这里POJO班:
@Document(collection = "sample_event")
public class SampleEvent implements Serializable{
@Id
private ObjectId id;
private Map<String, Object> fields = new HashMap<String, Object>();
public ObjectId getId() {
return id;
}
public void setId(ObjectId id) {
this.id = id;
}
@JsonAnyGetter
public Map<String, Object> any() {
return fields;
}
@JsonAnySetter
public void set(String name, Object value) {
fields.put(name, value);
}
public void setFields(Map<String, Object> obj) {
fields = obj;
}
public Map<String, Object> getFields() {
return fields;
}
}
我的主要课程:
@Autowired
private SampleEventRepository sampleEventRepository;
SampleEvent sampleEvent = new SampleEvent();
sampleEvent.setUniqueId("1.1.1.1");
sampleEvent.setFields(mapObj);
...
sampleEventRepository.save(sampleEvent);
答案 0 :(得分:1)
从Converter
&amp;更改SampleEvent
类型后,这项工作正常Document
至SampleEvent
&amp; DBObject
如下(适用于SampleEventWriterConverter
类)
@Component
public class SampleEventWriterConverter implements Converter<SampleEvent, DBObject> {
@Override
public DBObject convert(SampleEvent event) {
DBObject doc = new BasicDBObject ();
doc.put("_id", event.getId());
// …
doc.put("sample", "test");
for (Map.Entry<String, Object> entry : event.getFields().entrySet()) {
doc.put(entry.getKey(), entry.getValue());
}
return doc;
}
}