Skip to content

Commit 39ad336

Browse files
committed
add iterator to tutorial
1 parent 0b3971a commit 39ad336

1 file changed

Lines changed: 36 additions & 0 deletions

File tree

src/test/java/org/lmdbjava/TutorialTest.java

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,11 @@
3333
import org.junit.Rule;
3434
import org.junit.Test;
3535
import org.junit.rules.TemporaryFolder;
36+
import org.lmdbjava.CursorIterator.IteratorType;
37+
import org.lmdbjava.CursorIterator.KeyVal;
3638

39+
import static org.lmdbjava.CursorIterator.IteratorType.BACKWARD;
40+
import static org.lmdbjava.CursorIterator.IteratorType.FORWARD;
3741
import static org.lmdbjava.DbiFlags.MDB_CREATE;
3842
import static org.lmdbjava.DbiFlags.MDB_DUPSORT;
3943
import static org.lmdbjava.Env.create;
@@ -257,6 +261,38 @@ public void tutorial3() throws IOException {
257261
txn.commit();
258262
}
259263

264+
// Iterators are provided as a convenience. Each iterator
265+
// uses a cursor and must be closed when finished.
266+
267+
try (Txn<ByteBuffer> txn = env.txnWrite()) {
268+
269+
// iterate forward in terms of key ordering starting with the first key
270+
try (CursorIterator<ByteBuffer> it = db.iterate(txn, FORWARD)) {
271+
for (KeyVal<ByteBuffer> kv : it.iterable()) {
272+
ByteBuffer k = kv.key;
273+
ByteBuffer v = kv.val;
274+
}
275+
}
276+
277+
// iterate backward in terms of key ordering starting with the first key
278+
try (CursorIterator<ByteBuffer> it = db.iterate(txn, BACKWARD)) {
279+
for (KeyVal<ByteBuffer> kv : it.iterable()) {
280+
ByteBuffer k = kv.key;
281+
ByteBuffer v = kv.val;
282+
}
283+
}
284+
285+
// search for key and iterate forwards/backward from there til the last/first key.
286+
ByteBuffer searchKey = allocateDirect(511);
287+
searchKey.putLong(100L);
288+
try (CursorIterator<ByteBuffer> it = db.iterate(txn, searchKey, FORWARD)) {
289+
for (KeyVal<ByteBuffer> kv : it.iterable()) {
290+
ByteBuffer k = kv.key;
291+
ByteBuffer v = kv.val;
292+
}
293+
}
294+
}
295+
260296
// A read-only Cursor can survive its original Txn being closed. This is
261297
// useful if you want to close the original Txn (eg maybe you created the
262298
// Cursor during the constructor of a singleton with a throw-away Txn). Of

0 commit comments

Comments
 (0)