弹簧数据mongodb转换器

时间:2014-03-18 11:51:05

标签: mongodb spring-data

我正在使用spring数据mongo-db 1.4.1.RELEASE。

我的实体'Event'有一个基于其他属性计算的getter方法:

 public int getStatus() {
      return (getMainEventId() == null) ?  (elapseTimeInMin() < MINIMUM_TIME ? CANDIDATE : 
       VALID) : POINTER;
      }   

我希望只通过getter来保存属性'status',所以我写了转换器:

 @WritingConverter
    public class EventWriteConverter implements Converter<Event ,BasicDBObject > {



    static final Logger logger = LoggerFactory.getLogger(EventWriteConverter.class.getCanonicalName());

    public BasicDBObject convert(Event event) {

        logger.info("converting " +event );

        if (event.getMainEventId() != null)
            return new BasicDBObject("mainEventId", event.getMainEventId() );

        BasicDBObject doc = new BasicDBObject("status",event.getStatus()).
                append("updated_date",new Date()).
                append("start",event.getS0()).
                append("end",event.getS1()).
                append("location",event.getLocation()).

                ;

        BasicDBList list = new BasicDBList();


        doc.append("access_points",event.getHotPoints());

        return doc;
    }

    @ReadingConverter
    public class EventReadConverter implements Converter<BasicDBObject, Event> {

    @Inject
    HotPointRepositry hotRepositry;

    static final Logger logger = LoggerFactory.getLogger(EventReadConverter.class.getCanonicalName());

    public Event convert(BasicDBObject doc) {

        logger.info(" converting ");
        Event event = new Event();

        event.setId(doc.getObjectId("_id"));
        event.setS0(doc.getDate("start"));
        event.setS1(doc.getDate("end"));
        BasicDBList dblist = (BasicDBList) doc.get("hot_points");
        if (dblist != null) {

            for (Object obj : dblist) {

                ObjectId hotspotId = ((BasicDBObject) obj).getObjectId("_id");
                event.addHot(hotRepositry.findOne(hotId));
            }
        }
        dblist = (BasicDBList) doc.get("devices");
        if (dblist != null) {
            for (Object obj : dblist)
                event.addDevice(obj.toString());
        }



        event.setMainEventId(doc.getObjectId("mainEventId"));

        return event;

     }

    }

我的测试mongo配置是

@Profile("test")
@Configuration
@EnableMongoRepositories(basePackages = "com.echo.spring.data.mongo")
@ComponentScan(basePackages = "com.echo.spring.data.mongo" )
public class MongoDbTestConfig extends AbstractMongoConfiguration {


    static final Logger logger = LoggerFactory.getLogger(MongoDbTestConfig.class.getCanonicalName());
    @Override
    protected String getDatabaseName() {
        return "echo";
    }

    @Override
    public Mongo mongo() {
        return new Fongo("echo-test").getMongo();
    }

    @Override
    protected String getMappingBasePackage() {
        return "com.echo.spring.data.mongo";
    }
    @Bean
    @Override
    public CustomConversions customConversions() {
        logger.info("loading custom converters");
        List<Converter<?, ?>> converterList = new ArrayList<Converter<?, ?>>();
        converterList.add(new EventReadConverter());
        converterList.add(new EventWriteConverter());
        CustomConversions cus = new CustomConversions(converterList);

        return new CustomConversions(converterList);
    }
    }

我的测试(使用fongo)是

ActiveProfiles("test")
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MongoDbTestConfig.class  )
public class SampleMongoApplicationTests {

 @Test
@ShouldMatchDataSet(location = "/MongoJsonData/events.json")
public void shouldSaveEvent() throws IOException {

    URL url = Resources.getResource("MongoJsonData/events.json");
    List<String> lines = Resources.readLines(url,Charsets.UTF_8);

    for (String line : lines) {
        Event event =   objectMapper.readValue(line.getBytes(),Event.class);
        eventRepository.save(event);
    }

}

我可以看到在调用配置customConversions()时加载了转换器 我在转换方法中添加了日志记录和断点,但它们似乎不是 在我运行或调试时调用,尽管它们已加载。

我做错了什么?

1 个答案:

答案 0 :(得分:0)

我有类似的情况,我跟着Spring -Mongodb storing/retrieving enums as int not string 我需要连接转换器AND converterFactory以使其正常工作。