|
33 | 33 | import org.junit.Rule; |
34 | 34 | import org.junit.Test; |
35 | 35 | import org.junit.rules.TemporaryFolder; |
| 36 | +import org.lmdbjava.CursorIterator.IteratorType; |
| 37 | +import org.lmdbjava.CursorIterator.KeyVal; |
36 | 38 |
|
| 39 | +import static org.lmdbjava.CursorIterator.IteratorType.BACKWARD; |
| 40 | +import static org.lmdbjava.CursorIterator.IteratorType.FORWARD; |
37 | 41 | import static org.lmdbjava.DbiFlags.MDB_CREATE; |
38 | 42 | import static org.lmdbjava.DbiFlags.MDB_DUPSORT; |
39 | 43 | import static org.lmdbjava.Env.create; |
@@ -257,6 +261,38 @@ public void tutorial3() throws IOException { |
257 | 261 | txn.commit(); |
258 | 262 | } |
259 | 263 |
|
| 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 | + |
260 | 296 | // A read-only Cursor can survive its original Txn being closed. This is |
261 | 297 | // useful if you want to close the original Txn (eg maybe you created the |
262 | 298 | // Cursor during the constructor of a singleton with a throw-away Txn). Of |
|
0 commit comments