我如何在Spring Data中使用MongoRepository进行$ push?

时间:2013-01-09 22:20:54

标签: spring-data spring-data-mongodb

我有一个像这样的MongoDB结构:

record = { 'field': 'value', 
           'field2': 'value2',
           'events' : [ { 'event1': 1 }, { 'event2' : 2 }]
         }

我使用Spring Data MongoDB包来访问这些数据。主要是对数据进行写入,所以我想使用原生的“$ push”功能将“事件”添加到“记录”中,但我似乎无法弄清楚如何在没有获取的情况下使用MongoRepository。整个记录,然后将其推回并保存回来?

在使用MongoRepository时,您从未真正拥有过具体的实现。 Spring根据注释或方法本身的名称处理所有内容

更新

是否可以在存储库上实现自定义方法然后使用MongoTemplate手动执行此方法?

示例:

FooRepository.java

public interface FooRepository extends
    CrudRepository<Foo, ObjectId>,
        AppointmentWarehouseRepositoryCustom {
}

FooRepositoryCustom.java

public interface AppointmentWarehouseRepositoryCustom {
    public void pushMethod();
}

FooRepositoryImpl.java

public class FooRepositoryImpl implements
    AppointmentWarehouseRepositoryCustom {

    @Autowired
    protected MongoTemplate mongoTemplate;

    public void pushMethod() {
        // Push methods here. 
    }
}

2 个答案:

答案 0 :(得分:13)

是的,您必须在存储库上实现自定义方法,并且您的push方法将是这样的:

public class FooRepositoryImpl implements
    AppointmentWarehouseRepositoryCustom {

    @Autowired
    protected MongoTemplate mongoTemplate;

    public void pushMethod(String objectId, Object... events) {
        mongoTemplate.updateFirst(
            Query.query(Criteria.where("id").is(objectId)), 
            new Update().pushAll("events", events), Foo.class);
    }
}

答案 1 :(得分:5)

你可以这样做,但我遇到了一个问题,即没有保留“_class”字段。推送的对象本身是通过配置的转换器运行的,但由于某种原因,未写入该推送对象的“_class”字段。但是,如果我自己注入转换器并将对象写入DBObject,则保留并写入“_class”字段。因此变成:

public class FooRepositoryImpl implements
AppointmentWarehouseRepositoryCustom {

@Autowired
protected MongoTemplate mongoTemplate;

public void pushMethod(String objectId, Object event) {
    DBObject eventObj = new BasicDBObject();
    converter.write(event, eventObj);
    mongoTemplate.updateFirst(
        Query.query(Criteria.where("id").is(objectId)), 
        new Update().push("events", eventObj), Foo.class);
  }
}