0

我在使用 MongoJack 和 updateById 方法时遇到问题。

在来自 MongoJack 的 javadoc 中,它指出方法 updateById(K, T) (链接到 javadoc)可以使用 K 作为键和 T 作为要保存的对象。但是,以下代码和测试表明情况并非如此。完整的源代码可以在 Github 上找到:https ://github.com/nilsmagnus/mongojackupdatebyid/ 。

要保存的对象:

package no.nils.mongoupdate;

  public class Scenario {
  public String _id;
  public String name;

  public Scenario(String name) {
    this.name = name;
  }

  public String get_id() {
    return _id;
  }

  public String getName() {
    return name;
  }
}

更新类:

package no.nils.mongoupdate;

import org.mongojack.JacksonDBCollection;
import org.mongojack.WriteResult;
import com.mongodb.DB;
import com.mongodb.DBCollection;

class ScenarioStorage {
private JacksonDBCollection<Scenario, String> scenarioCollection;

public ScenarioStorage(DB db) {
    DBCollection dbCollection = db.getCollection("scenario");
    scenarioCollection = JacksonDBCollection.wrap(dbCollection, Scenario.class, String.class);
}

public void update(Scenario scenario) {
    WriteResult<Scenario, String> writeResult = scenarioCollection.updateById(scenario._id, scenario);
    if (writeResult.getError() != null) throw new RuntimeException(writeResult.getError());
}

public String saveNewScenario(Scenario scenario) {
    WriteResult<Scenario, String> writeResult = scenarioCollection.insert(scenario);
    if (writeResult.getError() != null) throw new RuntimeException(writeResult.getError());
    return writeResult.getSavedId();
}


public Scenario getScenario(String id) {
    return scenarioCollection.findOneById(id);
}
}

显示失败的测试:

package no.nils.mongoupdate;

import java.net.UnknownHostException;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

import org.junit.Before;
import org.junit.Test;
import com.mongodb.DB;
import com.mongodb.MongoClient;

public class ScenarioStorageTest {

private ScenarioStorage storage;

@Before
public void createDb() throws UnknownHostException {
    MongoClient mongoClient = new MongoClient("localhost", 27017);
    DB db = mongoClient.getDB("junittest");
    storage = new ScenarioStorage(db);
}

@Test
public void shouldUpdateNameAfterUpdate() {
    Scenario scenario = new Scenario("first");
    final String id = storage.saveNewScenario(scenario);
    scenario._id = id;
    scenario.name = "newname";
    storage.update(scenario);
    Scenario updated = storage.getScenario(id);
    assertNotNull("Stored object should have been fetched.", updated.name);
    assertEquals("The stored object should now have the name 'newname'.", updated.name, "newname");
}
}

测试在第一个断言上失败。如果我误解了 mongojack 的 javadoc 或我可能犯的任何其他错误,请告知。

4

1 回答 1

1

好的,javadoc 和教程坏了。解决方法是在 _id 字段中添加注解@ObjectId。

@ObjectId
public String _id;
于 2014-09-08T08:51:32.737 回答