AbacusUtil Docs | Download | Javadoc | FAQ | Community

MongoDBExecutor

MongoDBExecutor is a wrapper of MongoDB Java driver. Just like SQLExecutor, it makes things much easier to operate data with MongoDB by the straight support of Entity/Map/Query..., and almost all the java basic types: boolean...double...String...Date...Calendar.... Rather than introducing something new or different, MongoDBExecutor is created to make things simpler. Here is a simple sample:

static final MongoClient mongoClient = new MongoClient("localhost", 27017);
static final MongoDatabase mongoDB = mongoClient.getDatabase("test");
static final String collectionName = "account";
static final MongoDBExecutor dbExecutor = new MongoDBExecutor(mongoDB);
static final MongoCollectionExecutor collExecutor = dbExecutor.getCollExecutor(collectionName);
static final AsyncMongoCollectionExecutor asyncCollExecutor = collExecutor.asyncCollExecutor();

static {
    MongoDBExecutor.registerIdProeprty(Account.class, ID);
}

@Test
public void test_crud_by_id() {
    Account account = createAccount();
    account.setId(ObjectId.get().toString());

    // create
    collExecutor.insert(account);

    // read
    Account dbAccount = collExecutor.get(Account.class, account.getId());

    // update
    dbAccount.setFirstName("newFirstName");
    collExecutor.update(dbAccount.getId(), N.asMap(FIRST_NAME, dbAccount.getFirstName()));

    // delete
    collExecutor.delete(dbAccount.getId());

    // check
    assertFalse(collExecutor.exists(dbAccount.getId()));
}

@Test
public void test_crud() {
    Account account = createAccount();
    account.setId(null);

    // create
    collExecutor.insert(account);

    // read
    Account dbAccount = collExecutor.queryForEntity(Account.class, Filters.eq(LAST_NAME, account.getLastName()));

    // update
    dbAccount.setFirstName("newFirstName");
    collExecutor.update(Filters.eq(LAST_NAME, dbAccount.getLastName()), dbAccount);

    // delete
    collExecutor.delete(Filters.eq(FIRST_NAME, dbAccount.getFirstName()));

    // check
    assertFalse(collExecutor.exists(Filters.eq(LAST_NAME, dbAccount.getLastName())));
}

@Test
public void test_async_crud() throws Exception {
    Account account = createAccount();
    account.setId(null);

    // create
    asyncCollExecutor.insert(account).get();

    // read
    Account dbAccount = asyncCollExecutor.queryForEntity(Account.class, Filters.eq(LAST_NAME, account.getLastName())).get();

    // update
    dbAccount.setFirstName("newFirstName");
    asyncCollExecutor.update(Filters.eq(LAST_NAME, dbAccount.getLastName()), dbAccount).get();

    // delete
    asyncCollExecutor.delete(Filters.eq(FIRST_NAME, dbAccount.getFirstName())).get();

    // check
    assertFalse(asyncCollExecutor.exists(Filters.eq(LAST_NAME, dbAccount.getLastName())).get());
}

Try it now. Here are the steps: