initial import

This commit is contained in:
Greg Burd 2019-06-25 16:12:40 -04:00
commit 1d088e4a23
2967 changed files with 907449 additions and 0 deletions

58
.drone.yml Normal file
View file

@ -0,0 +1,58 @@
pipeline:
# Fetch folders from distributed cache
sftp_cache_restore:
image: plugins/sftp-cache
restore: true
mount:
- /drone/.ivy2/cache
- /drone/.coursier-cache
- /drone/.sbt
- /drone/.git
when:
event: [push, pull_request, tag, deployment]
tests:
image: scalaplatform/scala:0.6
volumes:
- /platform:/keys
commands:
- git fetch --tags && git log | head -n 20
- ./bin/cleanup_cache.sh
- sbt $CI_TEST
publish:
image: olafurpg/scalafix:0.3.0
pull: true
volumes:
- /platform:/keys
commands:
- ./bin/bintray.sh
when:
event: [push, tag]
branch: [master]
# Save folders in distributed cache
sftp_cache_rebuild:
image: plugins/sftp-cache
rebuild: true
mount:
- /drone/.ivy2/cache
- /drone/.coursier-cache
- /drone/.sbt
- /drone/.git
matrix:
include:
- CI_TEST: ci-fast
CI_SCALA_VERSION: 2.11.11
CI_PUBLISH: true
- CI_TEST: ci-fast
CI_SCALA_VERSION: 2.12.2
CI_PUBLISH: true
- CI_TEST: ci-sbt-stasis
CI_SCALA_VERSION: 2.12.2
- CI_TEST: ci-slow
CI_SCALA_VERSION: 2.11.11
- CI_TEST: ci-slow
CI_SCALA_VERSION: 2.12.2

0
.drone.yml.sig Normal file
View file

42
.github/ISSUE_TEMPLATE.md vendored Normal file
View file

@ -0,0 +1,42 @@
This template is a guideline, not a strict requirement.
- **Version**: 0.5
- **Integration**: IntelliJ
- **Configuration**:
```
maxColumn = 100
```
## Steps
Given code like this:
```scala
ORIGINAL CODE
```
When I use stasis like this:
```java
THE API CALLS I USED IN CONTEXT
```
## Problem
Stasis does the following:
```scala
OUTPUT FROM RUNNING THE EXAMPLE CODE
```
## Expectation
While I expected stasis to:
```scala
EXPECTED FORMATTING OUTPUT
```
## Workaround
I've found that by...
## Notes
See also..

9
.jvmopts Normal file
View file

@ -0,0 +1,9 @@
-Dfile.encoding=UTF8
-Xms1G
-Xmx3G
-XX:MaxMetaspaceSize=512M
-XX:ReservedCodeCacheSize=250M
-XX:+TieredCompilation
-XX:-UseGCOverheadLimit
-XX:+CMSClassUnloadingEnabled
-XX:+UseConcMarkSweepGC

1
.sbtopts Normal file
View file

@ -0,0 +1 @@
-J-XX:+CMSClassUnloadingEnabled

13
.scalafmt.conf Normal file
View file

@ -0,0 +1,13 @@
version=2.0.0-RC5
project.git = true
project.excludeFilters = [
scalafmt-benchmarks/src/resources,
sbt-test
bin/issue
]
align = none
# Disabled in default since this operation is potentially
# dangerous if you define your own stripMargin with different
# semantics from the stdlib stripMargin.
assumeStandardLibraryStripMargin = true
onTestFailure = "To fix this, run ./scalafmt from the project root directory"

41
.travis.yml Normal file
View file

@ -0,0 +1,41 @@
language: scala
stages:
- name: test
- name: release
if: (branch = master AND type = push) OR (tag IS present)
jobs:
include:
- env: TEST="stasis"
jdk: oraclejdk8
script: ./scalafmt --test
- env: TEST="2.11"
jdk: oraclejdk8
script: sbt ci-test
- env: TEST="2.12"
jdk: oraclejdk8
script: sbt ci-test
- env: TEST="2.11"
jdk: openjdk11
script: sbt ci-test
- env: TEST="2.12"
jdk: openjdk11
script: sbt ci-test
- stage: release
jdk: oraclejdk8
script: sbt ci-release docs/docusaurusPublishGhpages
cache:
directories:
- $HOME/.sbt
- $HOME/.ivy2/cache
- $HOME/.coursier
- target/repos
before_cache:
- du -h -d 1 $HOME/.ivy2/cache
- du -h -d 2 $HOME/.sbt/
- find $HOME/.sbt -name "*.lock" -type f -delete
- find $HOME/.ivy2/cache -name "ivydata-*.properties" -type f -delete
- rm -rf $HOME/.ivy2/local

2
CONTRIBUTING.md Normal file
View file

@ -0,0 +1,2 @@
# Contributing

201
LICENSE Normal file
View file

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

37
README.md Normal file
View file

@ -0,0 +1,37 @@
# Stasis
[![Build Status](https://travis-ci.org/stasis_io/stasis.svg?branch=master)](https://travis-ci.org/stasis_io/stasis)
[![Build status](https://ci.appveyor.com/api/projects/status/7gha7cxm5lw8fsc3)](https://ci.appveyor.com/project/stasis/stasis/branch/master)
[![Join the chat at https://gitter.im/stasis_io/stasis](https://badges.gitter.im/stasis_io/stasis.svg)](https://gitter.im/stasis/stasis?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![Latest version](https://index.scala-lang.org/stasis_io/stasis/scalafmt-core/latest.svg?color=orange)](https://index.scala-lang.org/stasis/stasis/stasis-core)
### [User documentation][docs]
Head over to [the user docs][docs] for instructions on how to install stasis.
### Quick help
- To build: `sbt compile`
- Run all unit tests: `sbt test`
- Build docs: See instructions on the [site][docs-guide] or locally at `./docs/contributing-website.md`.
- Run benchmarks: `./bin/run-benchmarks.sh`.
- Run formatter on millions of lines of code: `tests/test:runMain io.stasis.StasisProps` (slow, and requires a lot of memory/cpu)
- Debug performance: after each test run in `FormatTests`, a flamegraph report
like [this one](https://github.com/stasis/stasis/issues/140) is generated in `target/index.html`.
I usually keep a browser tab open at `localhost:3000/target/index.html` along with this background process:
`browser-sync start --server --files "target/*.html"`.
See [Browsersync](https://www.browsersync.io/).
### Team
The current maintainers (people who can merge pull requests) are:
* Gregory Burd - [`@gburd`](https://github.com/gburd)
An up-to-date list of contributors is available here: https://github.com/stasis/stasis/graphs/contributors but this
doesn't include the developers from Sleepycat and Oracle who maintained Berkeley DB Java Edition before it development
was halted in 2017. In 2019 the Stasis project started as a fork of JE.
We strive to offer a welcoming environment to learn, teach and contribute.
## Acknowledgments
[docs]: https://stasis.io/docs/

29
appveyor.yml Normal file
View file

@ -0,0 +1,29 @@
image:
- Visual Studio 2017
build: off
init:
- git config --global core.autocrlf input
install:
- ps: iex (new-object net.webclient).downloadstring('https://get.scoop.sh')
- ps: scoop bucket add versions
- ps: scoop install sbt
- SET SBT_OPTS=-XX:MaxPermSize=2g -Xmx4g -Dsbt.supershell=never -Dfile.encoding=UTF8
environment:
CI_SCALA_VERSION: 2.12.8
build_script:
- sbt downloadIdea tests/compile
test_script:
- sbt coreJVM/test
- sbt ci-test
cache:
- '%USERPROFILE%\.m2'
- '%USERPROFILE%\.ivy2\cache'
- '%USERPROFILE%\.sbt'
- '%USERPROFILE%\.coursier'
- '%USERPROFILE%\scoop\cache'

17
bin/run-benchmarks.sh Executable file
View file

@ -0,0 +1,17 @@
if [[ ! -f benchmarks/repos.tar.gz ]]; then
if [[ ! -f repos.tar.gz ]]; then
echo "Missing repos.tar.gz, run first sbt test"
exit 1
fi
echo "Extracting repos.tar.gz..."
cp repos.tar.gz benchmarks
cd benchmarks
tar xvf repos.tar.gz &> /dev/null
cd ..
echo "Done!"
fi
prefix=${1-Micro}
iterations=${2-3}
sbt "benchmarks/jmh:run -rf csv -rff target/jmh-results.csv -i $iterations -wi $iterations -f1 -t1 org.scalafmt.benchmarks.$prefix*"
# sbt "core/test:runMain org.scalafmt.FormatExperiment"

9
bin/test-release.sh Executable file
View file

@ -0,0 +1,9 @@
#!/usr/bin/env bash
set -eux
version=$1
coursier fetch io.stasis:stasis_2.12:$version -r sonatype:public
coursier fetch \
"io.stasis:sbt-stasis;sbtVersion=1.0;scalaVersion=2.12:$version" \
--sbt-plugin-hack -r sonatype:public

116
build.sbt Normal file
View file

@ -0,0 +1,116 @@
import Dependencies._
def scala211 = "2.11.12"
def scala212 = "2.12.8"
def scala213 = "2.13"
name := "stasis"
inThisBuild(
List(
organization := "io.stasis",
homepage := Some(url("https://github.com/stasis/stasis")),
licenses := List(
"Apache-2.0" -> url("http://www.apache.org/licenses/LICENSE-2.0"),
"ASM" -> url("https://asm.ow2.io/license.html")
),
developers := List(
Developer(
"gburd",
"Gregory Burd",
"greg@burd.me",
url("https://greg.burd.me")
)
),
scalaVersion := scala213,
crossScalaVersions := List(scala213, scala212, scala211),
resolvers += Resolver.sonatypeRepo("releases"),
libraryDependencies ++= List(
scalatest.value % Test,
scalacheck % Test,
scalametaTestkit % Test
)
)
)
skip in publish := true
commands += Command.command("ci-test") { s =>
val scalaVersion = sys.env.get("TEST") match {
case Some("2.11") => scala211
case Some("2.12") => scala212
case _ => scala213
}
val docsTest = if (scalaVersion == scala213) "docs/run" else "version"
s"++$scalaVersion" ::
s"tests/test" ::
s"coreJS/test" ::
docsTest ::
s
}
lazy val core = project
.in(file("stasis-core"))
.settings(
moduleName := "stasis-core",
description := "Implementation of Stasis",
buildInfoSettings,
buildInfoPackage := "io.stasis",
buildInfoObject := "BuildInfo",
libraryDependencies ++= List(
scalatest.value % Test,
scalametaTestkit % Test
)
)
.enablePlugins(BuildInfoPlugin)
lazy val cli = project
.in(file("stasis-cli"))
.settings(
moduleName := "stasis-cli",
mainClass in assembly := Some("io.stasis.cli.Cli"),
assemblyJarName.in(assembly) := "stasis.jar",
libraryDependencies ++= Seq(
"com.googlecode.java-diff-utils" % "diffutils" % "1.3.0",
"com.martiansoftware" % "nailgun-server" % "0.9.1",
"com.github.scopt" %% "scopt" % "3.5.0",
// undeclared transitive dependency of coursier-small
"org.scala-lang.modules" %% "scala-xml" % "1.1.1"
),
scalacOptions ++= {
CrossVersion.partialVersion(scalaVersion.value) match {
case Some((2, 11)) => Seq("-target:jvm-1.8")
case Some((2, 12)) => Seq("-target:jvm-1.8")
case Some((2, 13)) => Seq("-target:jvm-1.8")
case _ => Seq.empty
}
}
)
.dependsOn(core)
val V = "\\d+\\.\\d+\\.\\d+"
val ReleaseCandidate = s"($V-RC\\d+).*".r
val Milestone = s"($V-M\\d+).*".r
lazy val stableVersion = Def.setting {
version.in(ThisBuild).value.replaceAll("\\+.*", "")
}
lazy val buildInfoSettings: Seq[Def.Setting[_]] = Seq(
buildInfoKeys := Seq[BuildInfoKey](
name,
version,
"scalameta" -> scalametaV,
"nightly" -> version.value,
"stable" -> stableVersion.value,
"scala" -> scalaVersion.value,
"scala211" -> scala211,
"coursier" -> coursier,
"commit" -> sys.process.Process("git rev-parse HEAD").lineStream_!.head,
"timestamp" -> System.currentTimeMillis().toString,
scalaVersion,
sbtVersion
),
buildInfoPackage := "io.stasis",
buildInfoObject := "Versions"
)

0
docs/changelog.yml Normal file
View file

6
docs/configuration.md Normal file
View file

@ -0,0 +1,6 @@
---
id: configuration
title: Configuration
---
Configuration...

50
docs/contributing.md Normal file
View file

@ -0,0 +1,50 @@
---
id: contributing
title: Contributing
---
## Compiling project
- It's recommended to use Java 11.
- Build with `sbt`, to install sbt see https://www.scala-sbt.org/
- Use `sbt tests/test` instead of `sbt test`, the former runs modestly fast unit
tests for the JVM while `sbt test` is slower because it runs cross-platform
test and tests benchmark code and also compiles the documentation.
- You should be able to import the project into IntelliJ as normal:
`File -> New -> Project from existing source` and pick the `build.sbt` file.
## Opening pull requests
- **All code PRs should come with**: a meaningful description, inline-comments
for important things, unit tests (positive and negative), and a green build in
[CI](https://travis-ci.org/stasis/stasis).
- **Format your code with scalafmt**. Run `./scalafmt` from the project root
directory.
- **PRs for features should almost always include _some_ changes to the
[Documentation](https://stasis.io/docs)** as well.
- **Be prepared to discuss/advocate-for your changes if you want them merged**!
You will probably need to refactor so your changes fit into the larger
code base - **If your code is hard to unit test, and you don't want to unit
test it, that's okay**, but you will need to support your case.
- **The maintainers of this project might reject your changes** they might
rewrite them, or remove them in the future. This is normal and true for all
changes regardless of the author.
- **Even a rejected/reverted PR is valuable**! It helps explore the solution
space, and know what works and what doesn't. For every line in the repository,
there exists some rejected work.
- **Feel free to send Proof-Of-Concept PRs** that you don't intend to get
merged. Simply indicate that in the PR.
## Opening issues
Please always include concrete code examples with obtained and expected output.
## Releasing
- Ensure the release notes are up to date and complete.
- Pushing a git tag should trigger a release to Maven Central from the CI.
## Random stuff
-

9
docs/faq.md Normal file
View file

@ -0,0 +1,9 @@
---
id: faq
title: FAQ / Troubleshooting
---
## Why ...?
Because, reasons...

5
docs/gotchas.md Normal file
View file

@ -0,0 +1,5 @@
---
id: gotchas
title: Gotchas
---

7
docs/installation.md Normal file
View file

@ -0,0 +1,7 @@
---
id: installation
title: Installation
---
##

6
docs/introduction.md Normal file
View file

@ -0,0 +1,6 @@
---
id: introduction
title: Introduction
---
Visit [installation docs](installation.md)

10
docs/known-issues.md Normal file
View file

@ -0,0 +1,10 @@
---
id: known-issues
title: Known Issues
---
[Developing code formatters is notoriously hard](http://journal.stuffwithstuff.com/2015/09/08/the-hardest-program-ive-ever-written/)
and this project is no exception.
The following are the biggest known issues:

View file

@ -0,0 +1,458 @@
<!-- The excluded FindBugs warnings listed below are "known" and "ok".
Run FindBugs with this as an exclude file. For example:
findbugs -textui -exclude FindBugsExclude.xml je.jar
-->
<FindBugsFilter>
<Match class="com.sleepycat.collections.BlockIterator">
<BugCode name="REC" />
<Method name="add"/>
</Match>
<Match class="com.sleepycat.compat.DbCompat">
<BugCode name="MS" />
</Match>
<Match class="com.sleepycat.bind.serial.SerialOutput">
<BugCode name="MS" />
</Match>
<Match class="com.sleepycat.je.Database">
<BugCode name="IS" />
<Field name="handleLocker" />
</Match>
<Match class="com.sleepycat.je.DatabaseEntry">
<BugCode name="MS" />
<Field name="MAX_DUMP_BYTES" />
</Match>
<Match class="com.sleepycat.je.Environment">
<BugCode name="UG" />
<Method name="getMutableConfig"/>
</Match>
<Match class="com.sleepycat.je.dbi.DatabaseImpl">
<BugCode name="MS" />
<Field name="forceTreeWalkForTruncateAndRemove" />
</Match>
<Match class="com.sleepycat.je.dbi.MemoryBudget">
<BugCode name="MS" />
<Field name="CLEANUP_DONE" />
</Match>
<Match class="com.sleepycat.je.dbi.MemoryBudget">
<BugCode name="MS" />
<Field name="DEBUG_ADMIN" />
</Match>
<Match class="com.sleepycat.je.dbi.MemoryBudget">
<BugCode name="MS" />
<Field name="DEBUG_LOCK" />
</Match>
<Match class="com.sleepycat.je.dbi.MemoryBudget">
<BugCode name="MS" />
<Field name="DEBUG_TXN" />
</Match>
<Match class="com.sleepycat.je.dbi.MemoryBudget">
<BugCode name="MS" />
<Field name="DEBUG_TREEADMIN" />
</Match>
<Match class="com.sleepycat.je.dbi.MemoryBudget">
<BugCode name="MS" />
<Field name="DEBUG_TREE" />
</Match>
<Match class="com.sleepycat.persist.impl.PersistCatalog">
<BugCode name="MS" />
<Field name="expectNoClassChanges" />
</Match>
<Match class="com.sleepycat.persist.model.ClassEnhancer">
<BugCode name="RV" />
<Method name="enhanceFile"/>
</Match>
<Match class="com.sleepycat.je.txn.LockType">
<BugCode name="IC" />
</Match>
<Match class="com.sleepycat.je.log.LogEntryType">
<BugCode name="MS" />
</Match>
<Match class="com.sleepycat.je.log.LogUtils">
<BugCode name="MS" />
</Match>
<Match class="com.sleepycat.je.tree.BIN">
<BugCode name="Eq" />
</Match>
<Match class="com.sleepycat.je.tree.DIN">
<BugCode name="Eq" />
</Match>
<Match class="com.sleepycat.je.tree.DBIN">
<BugCode name="Eq" />
</Match>
<Match class="com.sleepycat.je.tree.DBINReference">
<BugCode name="Eq" />
</Match>
<Match class="com.sleepycat.collections.StoredMapEntry">
<BugCode name="Eq" />
</Match>
<Match class="com.sleepycat.je.log.StatsFileReader$LogEntryTypeComparator" >
<BugCode name="Se" />
</Match>
<Match class="com.sleepycat.je.log.FileManager">
<BugCode name="ST" />
</Match>
<Match class="com.sleepycat.je.log.FileManager">
<BugCode name="MS" />
<Field name="WRITE_COUNT" />
</Match>
<Match class="com.sleepycat.je.log.FileManager">
<BugCode name="MS" />
<Field name="STOP_ON_WRITE_COUNT" />
</Match>
<Match class="com.sleepycat.je.log.FileManager">
<BugCode name="MS" />
<Field name="N_BAD_WRITES" />
</Match>
<Match class="com.sleepycat.je.log.FileManager">
<BugCode name="MS" />
<Field name="THROW_ON_WRITE" />
</Match>
<Match class="com.sleepycat.persist.impl.Format">
<BugCode name="ST" />
<Method name="getReader"/>
</Match>
<Match class="com.sleepycat.je.log.ScavengerFileReader">
<BugCode name="NP" />
<Method name="resyncReader"/>
</Match>
<Match class="com.sleepycat.persist.impl.Evolver">
<BugCode name="NP" />
<Method name="evolveRequiredKeyField"/>
</Match>
<Match class="com.sleepycat.persist.impl.Evolver">
<BugCode name="NP" />
<Method name="evolveFormatInternal"/>
</Match>
<Match class="com.sleepycat.je.dbi.EnvironmentImpl">
<BugCode name="ST" />
</Match>
<Match class="com.sleepycat.je.dbi.EnvironmentImpl">
<BugCode name="ICAST" />
<Method name="updateBackgroundWrites"/>
</Match>
<Match class="com.sleepycat.je.dbi.EnvironmentImpl">
<BugCode name="SWL" />
<Method name="sleepAfterBackgroundIO"/>
</Match>
<Match class="com.sleepycat.je.TransactionStats$Active">
<BugCode name="SIC" />
</Match>
<Match class="com.sleepycat.je.evictor.Evictor">
<BugCode name="IS2" />
</Match>
<Match class="com.sleepycat.je.evictor.Evictor">
<BugCode name="IS" />
</Match>
<Match class="com.sleepycat.je.latch.SharedLatch">
<BugCode name="PS" />
</Match>
<Match class="com.sleepycat.je.latch.LatchImpl">
<BugCode name="IS" />
</Match>
<Match class="com.sleepycat.je.latch.SharedLatchImpl">
<BugCode name="IS" />
</Match>
<Match class="com.sleepycat.je.latch.Latch">
<BugCode name="IS2" />
</Match>
<Match class="com.sleepycat.je.latch.Latch">
<BugCode name="Wa" />
</Match>
<Match class="com.sleepycat.je.latch.Java5LatchImpl">
<BugCode name="IMSE" />
<Method name="doRelease" />
</Match>
<Match class="com.sleepycat.je.latch.Latch">
<BugCode name="IMSE" />
<Method name="doRelease" />
</Match>
<Match class="com.sleepycat.je.latch.Java5SharedLatchImpl" >
<BugCode name="SnVI" />
</Match>
<Match class="com.sleepycat.je.latch.Java5SharedLatchImpl">
<BugCode name="IMSE" />
<Method name="release" />
</Match>
<Match class="com.sleepycat.je.latch.SharedLatch">
<BugCode name="IMSE" />
<Method name="release" />
</Match>
<Match class="com.sleepycat.je.latch.Java5SharedLatchImpl">
<BugCode name="UL" />
<Method name="acquireExclusive" />
</Match>
<Match class="com.sleepycat.je.latch.Java5SharedLatchImpl">
<BugCode name="UL" />
<Method name="acquireShared" />
</Match>
<Match class="com.sleepycat.je.latch.SharedLatch">
<BugCode name="UL" />
<Method name="acquireExclusive" />
</Match>
<Match class="com.sleepycat.je.latch.SharedLatch">
<BugCode name="UL" />
<Method name="acquireShared" />
</Match>
<Match class="com.sleepycat.je.cleaner.Cleaner">
<BugCode name="IS2" />
</Match>
<Match class="com.sleepycat.je.cleaner.FileProcessor">
<BugCode name="IS" />
</Match>
<Match class="com.sleepycat.je.cleaner.UtilizationProfile">
<BugCode name="IS" />
</Match>
<Match class="com.sleepycat.je.recovery.Checkpointer">
<BugCode name="IS2" />
</Match>
<Match class="com.sleepycat.je.recovery.Checkpointer">
<BugCode name="ICAST" />
<Method name="isRunnable" />
</Match>
<Match class="com.sleepycat.je.recovery.Checkpointer">
<BugCode name="IS" />
</Match>
<Match class="com.sleepycat.je.recovery.RecoveryManager">
<BugCode name="REC" />
<Method name="readINsAndTrackIds"/>
</Match>
<Match class="com.sleepycat.je.recovery.RecoveryManager">
<BugCode name="REC" />
<Method name="redoLNs"/>
</Match>
<Match class="com.sleepycat.je.txn.Txn">
<BugCode name="IS2" />
</Match>
<Match class="com.sleepycat.je.txn.Txn">
<BugCode name="IS" />
</Match>
<Match class="com.sleepycat.collections.StoredMap">
<BugCode name="IS2" />
</Match>
<Match class="com.sleepycat.je.Sequence">
<BugCode name="IS2" />
</Match>
<Match class="com.sleepycat.je.Sequence">
<BugCode name="IS" />
</Match>
<Match class="com.sleepycat.je.incomp.INCompressor">
<BugCode name="IS,IS2,BC" />
</Match>
<Match class="com.sleepycat.je.tree.Key">
<BugCode name="MS" />
</Match>
<Match class="com.sleepycat.je.tree.IN">
<BugCode name="MS" />
</Match>
<Match class="com.sleepycat.je.tree.Tree">
<BugCode name="DMI" />
<Method name="validateINList" />
</Match>
<Match class="com.sleepycat.je.tree.Tree">
<BugCode name="NP" />
<Method name="deleteDupSubtree" />
</Match>
<Match class="com.sleepycat.je.tree.Tree">
<BugCode name="NP" />
<Method name="splitRoot" />
</Match>
<Match class="com.sleepycat.je.tree.Tree">
<BugCode name="NP" />
<Method name="searchSplitsAllowed" />
</Match>
<Match class="com.sleepycat.je.txn.Txn">
<BugCode name="MS" />
</Match>
<Match class="com.sleepycat.collections.StoredIterator">
<BugCode name="RV" />
<Method name="reset"/>
</Match>
<Match class="com.sleepycat.je.utilint.DaemonThread">
<BugCode name="RV" />
<Method name="checkErrorListener"/>
</Match>
<Match class="com.sleepycat.collections.DataView">
<BugCode name="DE" />
<Method name="join"/>
</Match>
<Match class="com.sleepycat.je.utilint.TracerFormatter">
<BugCode name="DE" />
<Method name="format"/>
</Match>
<Match class="com.sleepycat.je.incomp.INCompressor">
<BugCode name="RCN" />
<Method name="searchForBIN"/>
</Match>
<Match class="com.sleepycat.je.tree.Tree">
<BugCode name="RCN" />
<Method name="getNextBinInternal"/>
</Match>
<Match class="com.sleepycat.je.log.FSyncManager$FSyncGroup">
<BugCode name="NN" />
<Method name="wakeupOne"/>
</Match>
<Match class="com.sleepycat.je.txn.LockManager">
<BugCode name="NN" />
<Method name="release"/>
</Match>
<Match class="com.sleepycat.je.utilint.DaemonThread">
<BugCode name="UW" />
<Method name="run"/>
</Match>
<Match class="com.sleepycat.je.util.DbRunAction">
<BugCode name="REC" />
<Method name="main"/>
</Match>
<Match classregex="com.sleepycat.je.util.*" >
<BugCode name="Dm" />
</Match>
<Match class="com.sleepycat.asm.signature.SignatureWriter" >
<BugCode name="IM" />
<Method name="endArguments" />
</Match>
<Match class="com.sleepycat.asm.ClassReader" >
<BugCode name="Bx" />
<Method name="readAnnotationValue" />
</Match>
<Match class="com.sleepycat.asm.ClassReader" >
<BugCode name="Bx" />
<Method name="readConst" />
</Match>
<Match class="com.sleepycat.bind.serial.StoredClassCatalog$ClassInfo" >
<BugCode name="SnVI" />
</Match>
<Match classregex="com.sleepycat.persist.impl.*" >
<BugCode name="SnVI" />
</Match>
<Match class="com.sleepycat.persist.impl.ComplexFormat$SkipFieldReader">
<BugCode name="Se" />
<Field name="endField" />
</Match>
<Match class="com.sleepycat.persist.impl.EnumFormat" >
<BugCode name="Se" />
<Field name="values" />
</Match>
<Match class="com.sleepycat.persist.impl.FieldInfo" >
<BugCode name="Se" />
<Field name="cls" />
</Match>
<Match classregex=".*" >
<BugCode name="EI,EI2,CD" />
</Match>
<Match class="com.sleepycat.asm.Handler" >
<BugCode name="UrF" />
<Field name="desc" />
</Match>
<Match class="com.sleepycat.je.dbi.EnvironmentImpl" >
<BugCode name="UrF" />
<Field name="lockoutTimeout" />
</Match>
<!-- Match all doublecheck violations in these methods of "AnotherClass".
<Match class="com.foobar.AnotherClass">
<Or>
<Method name="nonOverloadedMethod" />
<Method name="frob" params="int,java.lang.String" returns="void" />
<Method name="blat" params="" returns="boolean" />
</Or>
<BugCode name="DC" />
</Match>
-->
</FindBugsFilter>

76
je-7.5.11/LICENSE Normal file
View file

@ -0,0 +1,76 @@
Copyright (C) 2002, 2016, Oracle and/or its affiliates. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License") reproduced below or available at:
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
1. You must give any other recipients of the Work or Derivative Works a copy of this License; and
2. You must cause any modified files to carry prominent notices stating that You changed the files; and
3. You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
4. If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
ADDITIONAL THIRD PARTY NOTICES:
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
/***
* ASM: a very small and fast Java bytecode manipulation framework
* Copyright (c) 2000-2005 INRIA, France Telecom
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/

5
je-7.5.11/README Normal file
View file

@ -0,0 +1,5 @@
Oracle: Berkeley DB, Java Edition 7.5.11: 2017-10-31 09:36:36 UTC
This is Berkeley DB, Java Edition, version 7.5.11 from
Oracle. To view the release and installation documentation, load
the distribution file docs/index.html into your web browser.

View file

@ -0,0 +1,16 @@
/*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2011, 2016 Oracle and/or its affiliates. All rights reserved.
*
*/
/**
* Print the value of the "sun.boot.class.path" system property, which is the
* boot classpath for the Oracle Java virtual machine.
*/
public class PrintBootClassPath {
public static void main(String[] args) {
System.out.println(System.getProperty("sun.boot.class.path"));
}
}

121
je-7.5.11/ant/compile.xml Normal file
View file

@ -0,0 +1,121 @@
<?xml version="1.0"?>
<project name="compile" default="compile" basedir=".">
<description>Shared compile target.</description>
<import file="${basedir}/build-common.xml"/>
<property name="include" value="com/sleepycat/**/*.java"/>
<property name="exclude1" value="com/sleepycat/**/jca/**/*.java"/>
<property name="exclude3" value="com/sleepycat/je/jmx/plugin/*.java"/>
<property name="exclude4" value="com/sleepycat/je/rep/jmx/plugin/*.java"/>
<!--
The sourcepath="" line must be specified in that way to clear out the field
and ensure that excludes takes effect.
jdk.source.version and jdk.target.version can be set to 1.6 to
compile for Java 6 source and bytecode, but this won't enforce the
runtime library. Use the compile-java6 target (below) instead when
building a release.
-->
<target name="compile" depends="get-jdk-source-boot-classpath">
<javac sourcepath=""
srcdir="${srcdir}"
includes="${include}"
excludes="${exclude1}, ${exclude2}, ${exclude3}, ${exclude4},
${exclude5}"
destdir="${destdir}"
classpathref="compile.classpath"
debug="${build.debug}"
deprecation="${build.deprecation}"
optimize="on"
includeantruntime="true"
source="${jdk.source.version}"
target="${jdk.target.version}"
bootclasspath="${jdk.source.boot.classpath}">
<!--
<compilerarg value="-Xlint:unchecked"/>
-->
</javac>
</target>
<!--
Compile for Java 6 source, bytecode and runtime libraries. This uses the
approach from the "Cross-Compilation Example" in the man page for javac,
version 1.7. The jdk6.home property must be set to use this target.
-->
<target name="compile-java6" depends="get-jdk6-boot-classpath">
<javac sourcepath=""
srcdir="${srcdir}"
includes="${include}"
excludes="${exclude1}, ${exclude2}, ${exclude3}, ${exclude4},
${exclude5}"
destdir="${destdir}"
classpathref="compile.classpath"
debug="${build.debug}"
deprecation="${build.deprecation}"
optimize="on"
includeantruntime="true"
source="1.6"
target="1.6"
bootclasspath="${jdk6.boot.classpath}"
extdirs="">
<!--
<compilerarg value="-Xlint:unchecked"/>
-->
</javac>
</target>
<!--
Store the Java 8 boot classpath in jdk.source.boot.classpath,
computing it by calling PrintBootClassPath using the Java 8 JVM
available in jdk8.home, if set.
-->
<target name="get-jdk-source-boot-classpath"
depends="compile-print-boot-classpath"
if="jdk8.home">
<java fork="yes"
jvm="${jdk8.home}/bin/java"
failonerror="true"
logerror="true"
classname="PrintBootClassPath"
classpath="${builddir}/tmp"
outputproperty="jdk.source.boot.classpath"/>
</target>
<!--
Store the Java 6 boot classpath in jdk6.boot.classpath, computing it
by calling PrintBootClassPath using the Java 6 JVM available in
jdk6.home, if set.
-->
<target name="get-jdk6-boot-classpath"
depends="compile-print-boot-classpath"
if="jdk6.home">
<java fork="yes"
jvm="${jdk6.home}/bin/java"
failonerror="true"
logerror="true"
classname="PrintBootClassPath"
classpath="${builddir}/tmp"
outputproperty="jdk6.boot.classpath"/>
</target>
<!--
Compile the PrintBootClassPath utility class, with 1.6 as the
target, so that we can use this with the Java 6 JVM.
-->
<target name="compile-print-boot-classpath">
<mkdir dir="${builddir}/tmp"/>
<javac srcdir="${basedir}/ant"
includes="PrintBootClassPath.java"
destdir="${builddir}/tmp"
includeantruntime="false"
debug="${build.debug}"
source="1.6"
target="1.6">
<!-- Ignore boot classpath warnings -->
<compilerarg value="-Xlint:-options"/>
</javac>
</target>
</project>

1187
je-7.5.11/ant/internal.xml Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,21 @@
<!--
Common definitions imported by build.xml, ant/compile.xml, etc.
-->
<project basedir=".">
<property name="srcdir" value="${basedir}/src"/>
<property name="builddir" value="${basedir}/build"/>
<property name="destdir" value="${builddir}/classes"/>
<property name="libdir" value="${builddir}/lib"/>
<property name="extlibdir" value="${basedir}/extlib"/>
<property name="ivy.lib.dir" value="${extlibdir}"/>
<property name="junit.jarfile" value="${extlibdir}/junit-4.10.jar"/>
<property name="hamcrest.jarfile" value="${extlibdir}/hamcrest-core-1.1.jar"/>
<property name="build.debug" value="on"/>
<property name="build.deprecation" value="off"/>
<!-- The JDK source and target versions for compiles and javadoc -->
<property name="jdk.source.version" value="1.8"/>
<property name="jdk.target.version" value="1.8"/>
</project>

2394
je-7.5.11/build.xml Normal file

File diff suppressed because it is too large Load diff

4
je-7.5.11/dist/build.properties vendored Normal file
View file

@ -0,0 +1,4 @@
release.version=7.5.11
release.numeric.version=7.5.11
release.major=7
release.minor=5

View file

@ -0,0 +1,214 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Chapter 9. Using Cursors</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="baseapi.html" title="Part II. Programming with the Base API" />
<link rel="prev" href="dbtUsage.html" title="Database Record Example" />
<link rel="next" href="Positioning.html" title="Getting Records Using the Cursor" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Chapter 9. Using Cursors</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="dbtUsage.html">Prev</a> </td>
<th width="60%" align="center">Part II. Programming with the Base API</th>
<td width="20%" align="right"> <a accesskey="n" href="Positioning.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="chapter" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title"><a id="Cursors"></a>Chapter 9. Using Cursors</h2>
</div>
</div>
</div>
<div class="toc">
<p>
<b>Table of Contents</b>
</p>
<dl>
<dt>
<span class="sect1">
<a href="Cursors.html#openCursor">Opening and Closing Cursors</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="Positioning.html">Getting Records Using the Cursor</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect2">
<a href="Positioning.html#diskorderedcursors">Disk Ordered Cursors</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="Positioning.html#cursorsearch">Searching for Records</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="Positioning.html#getdups">Working with Duplicate Records</a>
</span>
</dt>
</dl>
</dd>
<dt>
<span class="sect1">
<a href="PutEntryWCursor.html">Putting Records Using Cursors</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="DeleteEntryWCursor.html">Deleting Records Using Cursors</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="ReplacingEntryWCursor.html">Replacing Records Using Cursors</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="cursorUsage.html">Cursor Example</a>
</span>
</dt>
</dl>
</div>
<p>
Cursors provide a mechanism by which you can iterate over the records in a
database. Using cursors, you can get, put, and delete database records. If
a database allows duplicate records, then cursors are
<span>the only mechanism by
which you can access anything other than the first duplicate for a given
key.</span>
</p>
<p>
This chapter introduces cursors. It explains how to open and close them, how
to use them to modify databases, and how to use them with duplicate records.
</p>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="openCursor"></a>Opening and Closing Cursors</h2>
</div>
</div>
</div>
<p>
To use a cursor, you must open it using the <code class="methodname">Database.openCursor()</code>
method. When you open a
cursor, you can optionally pass it a <code class="classname">CursorConfig</code>
object to set cursor properties.
<span>
The cursor properties that you can set allows you to
determine whether the cursor will perform committed or
uncommitted reads. See the
<em class="citetitle">Berkeley DB, Java Edition Getting Started with Transaction Processing</em> guide for more
information.
</span>
</p>
<p>For example:</p>
<a id="je_cursor1"></a>
<pre class="programlisting">package je.gettingStarted;
import com.sleepycat.je.Cursor;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Environment;
import java.io.File;
...
Environment myDbEnvironment = null;
Database myDatabase = null;
Cursor myCursor = null;
try {
myDbEnvironment = new Environment(new File("/export/dbEnv"), null);
myDatabase = myDbEnvironment.openDatabase(null, "myDB", null);
myCursor = myDatabase.openCursor(null, null);
} catch (DatabaseException dbe) {
// Exception handling goes here ...
}</pre>
<p>
To close the cursor, call the <code class="methodname">Cursor.close()</code>
method. Note that if you close a database that has cursors open in it,
then it will throw an exception and close any open cursors for you.
For best results, close your cursors from within a
<code class="literal">finally</code> block. However, it is recommended that you always close all cursor handles immediately after their use to ensure concurrency and to release resources such as page locks.
<span></span>
</p>
<a id="je_cursor2"></a>
<pre class="programlisting">package je.gettingStarted;
import com.sleepycat.je.Cursor;
import com.sleepycat.je.Database;
import com.sleepycat.je.Environment;
...
try {
...
} catch ... {
} finally {
try {
if (myCursor != null) {
myCursor.close();
}
if (myDatabase != null) {
myDatabase.close();
}
if (myDbEnvironment != null) {
myDbEnvironment.close();
}
} catch(DatabaseException dbe) {
System.err.println("Error in close: " + dbe.toString());
}
} </pre>
</div>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="dbtUsage.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="baseapi.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="Positioning.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Database Record Example </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Getting Records Using the Cursor</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,157 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Administrative Methods</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="databases.html" title="Chapter 7. Databases" />
<link rel="prev" href="dbprops.html" title="Database Properties" />
<link rel="next" href="dbUsage.html" title="Database Example" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Administrative Methods</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="dbprops.html">Prev</a> </td>
<th width="60%" align="center">Chapter 7. Databases</th>
<td width="20%" align="right"> <a accesskey="n" href="dbUsage.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="DBAdmin"></a>Administrative Methods</h2>
</div>
</div>
</div>
<p>
Both the <code class="classname">Environment</code> and
<code class="classname">Database</code> classes provide methods that are useful
for manipulating databases. These methods are:
</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>
<code class="methodname">Database.getDatabaseName()</code>
</p>
<p>Returns the database's name.</p>
<a id="je_db3.1"></a>
<pre class="programlisting">String dbName = myDatabase.getDatabaseName();</pre>
<span>
</span>
</li>
<li>
<p>
<code class="methodname">Database.getEnvironment()</code>
</p>
<p>Returns the <code class="classname">Environment</code> that contains this database.</p>
<a id="je_db4"></a>
<pre class="programlisting">Environment theEnv = myDatabase.getEnvironment();</pre>
</li>
<li>
<p>
<code class="methodname">Database.preload()</code>
</p>
<p>Preloads the database into the in-memory cache. Optionally takes
a <code class="literal">long</code> that identifies the maximum number of bytes to load into the
cache. If this parameter is not supplied, the maximum memory usage
allowed by the evictor thread is used.
</p>
<a id="je_db6"></a>
<pre class="programlisting">myDatabase.preload(1048576l); // 1024*1024</pre>
</li>
<li>
<p>
<code class="methodname">Environment.getDatabaseNames()</code>
</p>
<p>Returns a list of Strings of all the databases contained by the
environment.</p>
<a id="je_db7"></a>
<pre class="programlisting">import java.util.List;
...
List myDbNames = myDbEnv.getDatabaseNames();
for(int i=0; i &lt; myDbNames.size(); i++) {
System.out.println("Database Name: " + (String)myDbNames.get(i));
}</pre>
</li>
<li>
<p>
<code class="methodname">Environment.removeDatabase()</code>
</p>
<p>Deletes the database. The database must be closed when you
perform this action on it.</p>
<a id="je_db8"></a>
<pre class="programlisting">String dbName = myDatabase.getDatabaseName();
myDatabase.close();
myDbEnv.removeDatabase(null, dbName);</pre>
</li>
<li>
<p>
<code class="methodname">Environment.renameDatabase()</code>
</p>
<p>Renames the database. The database must be closed when you
perform this action on it.</p>
<a id="je_db9"></a>
<pre class="programlisting">String oldName = myDatabase.getDatabaseName();
String newName = new String(oldName + ".new", "UTF-8");
myDatabase.close();
myDbEnv.renameDatabase(null, oldName, newName);</pre>
</li>
<li>
<p>
<code class="methodname">Environment.truncateDatabase()</code>
</p>
<p>
Deletes every record in the database and optionally returns the
number of records that were deleted. Note that it is much less
expensive to truncate a database without counting the number of
records deleted than it is to truncate and count.
</p>
<a id="je_db5"></a>
<pre class="programlisting">int numDiscarded =
myEnv.truncate(null, // txn handle
myDatabase.getDatabaseName(), // database name
true); // If true, then the
// number of records
// deleted are counted.
System.out.println("Discarded " + numDiscarded +
" records from database " +
myDatabase.getDatabaseName()); </pre>
</li>
</ul>
</div>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="dbprops.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="databases.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="dbUsage.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Database Properties </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Database Example</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,303 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Chapter 8. Database Records</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="baseapi.html" title="Part II. Programming with the Base API" />
<link rel="prev" href="dbUsage.html" title="Database Example" />
<link rel="next" href="usingDbt.html" title="Reading and Writing Database Records" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Chapter 8. Database Records</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="dbUsage.html">Prev</a> </td>
<th width="60%" align="center">Part II. Programming with the Base API</th>
<td width="20%" align="right"> <a accesskey="n" href="usingDbt.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="chapter" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title"><a id="DBEntry"></a>Chapter 8. Database Records</h2>
</div>
</div>
</div>
<div class="toc">
<p>
<b>Table of Contents</b>
</p>
<dl>
<dt>
<span class="sect1">
<a href="DBEntry.html#usingDbEntry">Using Database Records</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="usingDbt.html">Reading and Writing Database Records</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect2">
<a href="usingDbt.html#databaseWrite">Writing Records to the Database</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="usingDbt.html#databaseRead">Getting Records from the Database</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="usingDbt.html#recordDelete">Deleting Records</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="usingDbt.html#datapersist">Data Persistence</a>
</span>
</dt>
</dl>
</dd>
<dt>
<span class="sect1">
<a href="timetolive.html">Using Time to Live</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect2">
<a href="timetolive.html#ttl-specify">Specifying a TTL Value</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="timetolive.html#ttl-update">Updating a TTL Value</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="timetolive.html#ttl-remove">Deleting TTL Expiration</a>
</span>
</dt>
</dl>
</dd>
<dt>
<span class="sect1">
<a href="bindAPI.html">Using the BIND APIs</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect2">
<a href="bindAPI.html#bindPrimitive">Numerical and String Objects</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="bindAPI.html#object2dbt">Serializable Complex Objects</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="bindAPI.html#customTuple">Custom Tuple Bindings</a>
</span>
</dt>
</dl>
</dd>
<dt>
<span class="sect1">
<a href="comparator.html">Using Comparators</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect2">
<a href="comparator.html#writeCompare">Writing Comparators</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="comparator.html#setCompare">Setting Comparators</a>
</span>
</dt>
</dl>
</dd>
<dt>
<span class="sect1">
<a href="dbtUsage.html">Database Record Example</a>
</span>
</dt>
</dl>
</div>
<p>
JE records contain two parts — a key and some data. Both the key
and its corresponding data are
encapsulated in
<span><code class="classname">DatabaseEntry</code> class objects.</span>
Therefore, to access a JE record, you need two such
<span>objects,</span> one for the key and
one for the data.
</p>
<p>
<code class="classname">DatabaseEntry</code> can hold any kind of data from simple
Java primitive types to complex Java objects so long as that data can be
represented as a Java <code class="literal">byte</code> array. Note that due to
performance considerations, you should not use Java serialization to convert
a Java object to a <code class="literal">byte</code> array. Instead, use the Bind APIs
to perform this conversion (see
<a class="xref" href="bindAPI.html" title="Using the BIND APIs">Using the BIND APIs</a> for more
information).
</p>
<p>
This chapter describes how you can convert both Java primitives and Java
class objects into and out of <code class="literal">byte</code> arrays. It also
introduces storing and retrieving key/value pairs from a database. In
addition, this chapter describes how you can use comparators to influence
how JE sorts its database records.
</p>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="usingDbEntry"></a>Using Database Records</h2>
</div>
</div>
</div>
<p>
Each database record is comprised of two
<span><code class="classname">DatabaseEntry</code> objects</span>
— one for the key and another for the data.
<span>The key and data information are passed to-
and returned from JE using
<code class="classname">DatabaseEntry</code> objects as <code class="literal">byte</code>
arrays. Using <code class="classname">DatabaseEntry</code>s allows JE to
change the underlying byte array as well as return multiple values (that
is, key and data). Therefore, using <code class="classname">DatabaseEntry</code> instances
is mostly an exercise in efficiently moving your keys and your data in
and out of <code class="literal">byte</code> arrays.</span>
</p>
<p>
For example, to store a database record where both the key and the
data are Java <code class="classname">String</code> objects, you instantiate a
pair of <code class="classname">DatabaseEntry</code> objects:
</p>
<a id="je_dbt1"></a>
<pre class="programlisting">package je.gettingStarted;
import com.sleepycat.je.DatabaseEntry;
...
String aKey = "key";
String aData = "data";
try {
DatabaseEntry theKey = new DatabaseEntry(aKey.getBytes("UTF-8"));
DatabaseEntry theData = new DatabaseEntry(aData.getBytes("UTF-8"));
} catch (Exception e) {
// Exception handling goes here
}
// Storing the record is described later in this chapter </pre>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;">
<h3 class="title">Note</h3>
<p>
Notice that we specify <code class="literal">UTF-8</code> when we retrieve the
<code class="literal">byte</code> array from our <code class="classname">String</code>
object. Without parameters, <code class="methodname">String.getBytes()</code> uses the
Java system's default encoding. You should never use a system's default
encoding when storing data in a database because the encoding can change.
</p>
</div>
<p>
When the record is retrieved from the database, the method that you
use to perform this operation populates two <code class="classname">DatabaseEntry</code>
instances for you, one for the key and another for the data. Assuming Java
<code class="classname">String</code> objects, you retrieve your data from the
<code class="classname">DatabaseEntry</code> as follows:
</p>
<a id="je_dbt2"></a>
<pre class="programlisting">package je.gettingStarted;
import com.sleepycat.je.DatabaseEntry;
...
// theKey and theData are DatabaseEntry objects. Database
// retrieval is described later in this chapter. For now,
// we assume some database get method has populated these
// objects for us.
// Use DatabaseEntry.getData() to retrieve the encapsulated Java
// byte array.
byte[] myKey = theKey.getData();
byte[] myData = theData.getData();
String key = new String(myKey, "UTF-8");
String data = new String(myData, "UTF-8"); </pre>
<p>
There are a large number of mechanisms that you can use to move data in
and out of <code class="literal">byte</code> arrays. To help you with this
activity, JE provides the bind APIs. These APIs allow you to
efficiently store both primitive data types and complex objects in
<code class="literal">byte</code> arrays.
</p>
<p>
The next section describes basic database put and get operations. A
basic understanding of database access is useful when describing database
storage of more complex data such as is supported by the bind APIs. Basic
bind API usage is then described in <a class="xref" href="bindAPI.html" title="Using the BIND APIs">Using the BIND APIs</a>.
</p>
<span>
</span>
</div>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="dbUsage.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="baseapi.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="usingDbt.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Database Example </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Reading and Writing Database Records</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,122 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Deleting Records Using Cursors</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="Cursors.html" title="Chapter 9. Using Cursors" />
<link rel="prev" href="PutEntryWCursor.html" title="Putting Records Using Cursors" />
<link rel="next" href="ReplacingEntryWCursor.html" title="Replacing Records Using Cursors" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Deleting Records Using Cursors</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="PutEntryWCursor.html">Prev</a> </td>
<th width="60%" align="center">Chapter 9. Using Cursors</th>
<td width="20%" align="right"> <a accesskey="n" href="ReplacingEntryWCursor.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="DeleteEntryWCursor"></a>Deleting Records Using Cursors</h2>
</div>
</div>
</div>
<p>
To delete a record using a cursor, simply position the cursor to the
record that you want to delete and then call
<span>
<code class="methodname">Cursor.delete()</code>.
Note that after deleting a
record, the value of <code class="methodname">Cursor.getCurrent()</code>
is unchanged until such a
time as the cursor is moved again. Also, if you call
<code class="methodname">Cursor.delete()</code> two or more times in a row
without repositioning the cursor, then all subsequent deletes result in
a return value of <code class="literal">OperationStatus.KEYEMPTY</code>.
</span>
</p>
<p>For example:</p>
<a id="je_cursor8"></a>
<pre class="programlisting">package je.gettingStarted;
import com.sleepycat.je.Cursor;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.LockMode;
import com.sleepycat.je.OperationStatus;
...
Cursor cursor = null;
try {
...
// Database and environment open omitted for brevity
...
// Create DatabaseEntry objects
// searchKey is some String.
DatabaseEntry theKey = new DatabaseEntry(searchKey.getBytes("UTF-8"));
DatabaseEntry theData = new DatabaseEntry();
// Open a cursor using a database handle
cursor = myDatabase.openCursor(null, null);
// Position the cursor. Ignoring the return value for clarity
OperationStatus retVal = cursor.getSearchKey(theKey, theData,
LockMode.DEFAULT);
// Count the number of records using the given key. If there is only
// one, delete that record.
if (cursor.count() == 1) {
System.out.println("Deleting " +
new String(theKey.getData(), "UTF-8") +
"|" +
new String(theData.getData(), "UTF-8"));
cursor.delete();
}
} catch (Exception e) {
// Exception handling goes here
} finally {
// Make sure to close the cursor
cursor.close();
}</pre>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="PutEntryWCursor.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="Cursors.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="ReplacingEntryWCursor.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Putting Records Using Cursors </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Replacing Records Using Cursors</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,263 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Environment Properties</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="env.html" title="Chapter 2. Database Environments" />
<link rel="prev" href="envclose.html" title="Closing Database Environments" />
<link rel="next" href="envStats.html" title="Environment Statistics" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Environment Properties</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="envclose.html">Prev</a> </td>
<th width="60%" align="center">Chapter 2. Database Environments</th>
<td width="20%" align="right"> <a accesskey="n" href="envStats.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="EnvProps"></a>Environment Properties</h2>
</div>
</div>
</div>
<div class="toc">
<dl>
<dt>
<span class="sect2">
<a href="EnvProps.html#envconfig">The EnvironmentConfig Class</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="EnvProps.html#envhandleconfig">EnvironmentMutableConfig</a>
</span>
</dt>
</dl>
</div>
<p>
You set properties for the <code class="classname">Environment</code> using the
<code class="classname">EnvironmentConfig</code> class. You can also set properties for a
specific <code class="classname">Environment</code> instance using
<code class="classname">EnvironmentMutableConfig</code>.
</p>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="envconfig"></a>The EnvironmentConfig Class</h3>
</div>
</div>
</div>
<p>
The <code class="classname">EnvironmentConfig</code> class makes a large number of fields and
methods available to you. Describing all of these tuning parameters is beyond the scope of
this manual. However, there are a few properties that you are likely to want to set. They
are described here.
</p>
<p>
Note that for each of the properties that you can commonly set, there is a corresponding
getter method. Also, you can always retrieve the
<code class="classname">EnvironmentConfig</code> object used by your environment using the
<code class="methodname">Environment.getConfig()</code> method.
</p>
<p>
You set environment configuration parameters using the following methods on the
<code class="classname">EnvironmentConfig</code> class:
</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>
<code class="methodname">EnvironmentConfig.setAllowCreate()</code>
</p>
<p>
If <code class="literal">true</code>, the database environment is created when it is opened.
If <code class="literal">false</code>, environment open fails if the environment does not
exist. This property has no meaning if the database environment already exists.
Default is <code class="literal">false</code>.
</p>
</li>
<li>
<p>
<code class="methodname">EnvironmentConfig.setReadOnly()</code>
</p>
<p>If <code class="literal">true</code>, then all databases opened in this
environment must be opened as read-only. If you are writing a
multi-process application, then all but one of your processes must set
this value to <code class="literal">true</code>. Default is <code class="literal">false</code>.</p>
<p>
You can also set this property using the <code class="literal">je.env.isReadOnly</code>
parameter in your <code class="filename"><span class="emphasis"><em>env_home</em></span>/je.properties</code> file.
</p>
</li>
<li>
<p>
<code class="methodname">EnvironmentConfig.setTransactional()</code>
</p>
<p>If <code class="literal">true</code>, configures the database environment
to support transactions. Default is <code class="literal">false</code>.</p>
<p>
You can also set this property using the <code class="literal">je.env.isTransactional</code>
parameter in your <code class="filename"><span class="emphasis"><em>env_home</em></span>/je.properties</code> file.
</p>
</li>
</ul>
</div>
<p>For example:</p>
<a id="je_env3"></a>
<pre class="programlisting">package je.gettingStarted;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;
import java.io.File;
...
Environment myDatabaseEnvironment = null;
try {
EnvironmentConfig envConfig = new EnvironmentConfig();
envConfig.setAllowCreate(true);
envConfig.setTransactional(true);
myDatabaseEnvironment =
new Environment(new File("/export/dbEnv"), envConfig);
} catch (DatabaseException dbe) {
System.err.println(dbe.toString());
System.exit(1);
} </pre>
</div>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="envhandleconfig"></a>EnvironmentMutableConfig</h3>
</div>
</div>
</div>
<p>
<code class="classname">EnvironmentMutableConfig</code> manages properties that can be reset after the
<code class="classname">Environment</code> object has been constructed. In addition, <code class="classname">EnvironmentConfig</code>
extends <code class="classname">EnvironmentMutableConfig</code>, so you can set these mutable properties at
<code class="classname">Environment</code> construction time if necessary.
</p>
<p>
The <code class="classname">EnvironmentMutableConfig</code> class allows you to set the following
properties:
</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>
<code class="literal">setCachePercent()</code>
</p>
<p>
Determines the percentage of JVM memory available to the JE cache.
See
<a class="xref" href="cachesize.html" title="Sizing the Cache">Sizing the Cache</a>
for more information.
</p>
</li>
<li>
<p>
<code class="literal">setCacheSize()</code>
</p>
<p>
Determines the total amount of memory available to the database cache.
See <a class="xref" href="cachesize.html" title="Sizing the Cache">Sizing the Cache</a>
for more information.
</p>
</li>
<li>
<p>
<code class="literal">setTxnNoSync()</code>
</p>
<p>
Determines whether change records created due to a transaction commit are written to the backing
log files on disk. A value of <code class="literal">true</code> causes
the data to not be flushed to
disk. See the <em class="citetitle">Berkeley DB, Java Edition Getting Started with Transaction Processing</em> guide.
</p>
</li>
<li>
<p>
<code class="literal">setTxnWriteNoSync()</code>
</p>
<p>
Determines whether logs are flushed on transaction commit (the logs are still written, however).
By setting this value to <code class="literal">true</code>, you potentially gain better performance than if
you flush the logs on commit, but you do so by losing some of your transaction durability guarantees.
</p>
</li>
</ul>
</div>
<p>
There is also a corresponding getter method (<code class="methodname">getTxnNoSync()</code>).
Moreover, you can always retrieve your environment's
<code class="classname">EnvironmentMutableConfig</code> object by
using the <code class="methodname">Environment.getMutableConfig()</code> method.
</p>
<p>
For example:
</p>
<a id="je_env4"></a>
<pre class="programlisting">package je.gettingStarted;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentMutableConfig;
import java.io.File;
...
try {
Environment myEnv = new Environment(new File("/export/dbEnv"), null);
EnvironmentMutableConfig envMutableConfig =
new EnvironmentMutableConfig();
envMutableConfig.setTxnNoSync(true);
myEnv.setMutableConfig(envMutableConfig);
} catch (DatabaseException dbe) {
// Exception handling goes here
} </pre>
</div>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="envclose.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="env.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="envStats.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Closing Database Environments </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Environment Statistics</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,691 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Getting Records Using the Cursor</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="Cursors.html" title="Chapter 9. Using Cursors" />
<link rel="prev" href="Cursors.html" title="Chapter 9. Using Cursors" />
<link rel="next" href="PutEntryWCursor.html" title="Putting Records Using Cursors" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Getting Records Using the Cursor</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="Cursors.html">Prev</a> </td>
<th width="60%" align="center">Chapter 9. Using Cursors</th>
<td width="20%" align="right"> <a accesskey="n" href="PutEntryWCursor.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="Positioning"></a>Getting Records Using the Cursor</h2>
</div>
</div>
</div>
<div class="toc">
<dl>
<dt>
<span class="sect2">
<a href="Positioning.html#diskorderedcursors">Disk Ordered Cursors</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="Positioning.html#cursorsearch">Searching for Records</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="Positioning.html#getdups">Working with Duplicate Records</a>
</span>
</dt>
</dl>
</div>
<p>
To iterate over database records, from the first record to
the last, simply open the cursor and then use the
<code class="methodname">Cursor.getNext()</code>
method.
For example:
</p>
<a id="je_cursor3"></a>
<pre class="programlisting">package je.gettingStarted;
import com.sleepycat.je.Cursor;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.LockMode;
import com.sleepycat.je.OperationStatus;
...
Cursor cursor = null;
try {
...
// Database and environment open omitted for brevity
...
// Open the cursor.
cursor = myDatabase.openCursor(null, null);
// Cursors need a pair of DatabaseEntry objects to operate. These hold
// the key and data found at any given position in the database.
DatabaseEntry foundKey = new DatabaseEntry();
DatabaseEntry foundData = new DatabaseEntry();
// To iterate, just call getNext() until the last database record has
// been read. All cursor operations return an OperationStatus, so just
// read until we no longer see OperationStatus.SUCCESS
while (cursor.getNext(foundKey, foundData, LockMode.DEFAULT) ==
OperationStatus.SUCCESS) {
// getData() on the DatabaseEntry objects returns the byte array
// held by that object. We use this to get a String value. If the
// DatabaseEntry held a byte array representation of some other
// data type (such as a complex object) then this operation would
// look considerably different.
String keyString = new String(foundKey.getData(), "UTF-8");
String dataString = new String(foundData.getData(), "UTF-8");
System.out.println("Key | Data : " + keyString + " | " +
dataString + "");
}
} catch (DatabaseException de) {
System.err.println("Error accessing database." + de);
} finally {
// Cursors must be closed.
cursor.close();
}</pre>
<p>
To iterate over the database from the last record to the first,
instantiate the cursor, and then
use <code class="methodname">Cursor.getPrev()</code> until you read the first record in
the database. For example:
</p>
<a id="je_cursor4"></a>
<pre class="programlisting">package je.gettingStarted;
import com.sleepycat.je.Cursor;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.LockMode;
import com.sleepycat.je.OperationStatus;
...
Cursor cursor = null;
try {
...
// Database and environment open omitted for brevity
...
// Open the cursor.
cursor = myDatabase.openCursor(null, null);
// Get the DatabaseEntry objects that the cursor will use.
DatabaseEntry foundKey = new DatabaseEntry();
DatabaseEntry foundData = new DatabaseEntry();
// Iterate from the last record to the first in the database
while (cursor.getPrev(foundKey, foundData, LockMode.DEFAULT) ==
OperationStatus.SUCCESS) {
String theKey = new String(foundKey.getData(), "UTF-8");
String theData = new String(foundData.getData(), "UTF-8");
System.out.println("Key | Data : " + theKey + " | " +
theData + "");
}
} catch (DatabaseException de) {
System.err.println("Error accessing database." + de);
} finally {
// Cursors must be closed.
cursor.close();
}</pre>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="diskorderedcursors"></a>Disk Ordered Cursors</h3>
</div>
</div>
</div>
<p>
The previous example shows how to scan through the records in
your database sequentially; that is, in the record's sort order.
This is mostly determined by the value contained in the records' keys
(additional sorting is required in the case of duplicate
records). However, you can use cursors to retrieve records based
on how they are stored on disk. This can improve retrieval times,
and is useful if your application needs to scan all the records
in the database quickly, without concern for key sort order.
You do this using the <code class="classname">DiskOrderedCursor</code>
class.
</p>
<p>
<code class="classname">DiskOrderedClass</code> works in the same way as
a regular cusor: you simply open the cursor, then retrieve
records one after another using the
<code class="methodname">DiskOrderedClass.getNext()</code>
method.
</p>
<p>
You open a <code class="classname">DiskOrderedCursor</code>
using the <code class="methodname">Database.openCursor()</code>
method. This version of the method takes a single parameter: an
instance of the
<code class="classname">DiskOrderedCursorConfig</code>
class, which can be used to configure various aspects of the
<code class="classname">DiskOrderedCursor</code>
class.
</p>
<a id="je_diskorderedcursor1"></a>
<pre class="programlisting">package je.gettingStarted;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.DiskOrderedCursor;
import com.sleepycat.je.DiskOrderedCursorConfig;
import com.sleepycat.je.LockMode;
import com.sleepycat.je.OperationStatus;
...
DiskOrderedCursor dcursor = null;
DiskOrderedCursorConfig docc = new DiskOrderedCursorConfig();
try {
...
// Database and environment open omitted for brevity
...
// Open the cursor.
dcursor = myDatabase.openCursor(docc);
// Cursors need a pair of DatabaseEntry objects to operate. These hold
// the key and data found at any given position in the database.
DatabaseEntry foundKey = new DatabaseEntry();
DatabaseEntry foundData = new DatabaseEntry();
// To iterate, just call getNext() until the last database record has
// been read. All cursor operations return an OperationStatus, so just
// read until we no longer see OperationStatus.SUCCESS
while (dcursor.getNext(foundKey, foundData, LockMode.DEFAULT) ==
OperationStatus.SUCCESS) {
// getData() on the DatabaseEntry objects returns the byte array
// held by that object. We use this to get a String value. If the
// DatabaseEntry held a byte array representation of some other
// data type (such as a complex object) then this operation would
// look considerably different.
String keyString = new String(foundKey.getData(), "UTF-8");
String dataString = new String(foundData.getData(), "UTF-8");
System.out.println("Key | Data : " + keyString + " | " +
dataString + "");
}
} catch (DatabaseException de) {
System.err.println("Error accessing database." + de);
} finally {
// Cursors must be closed.
cursor.close();
}</pre>
</div>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="cursorsearch"></a>Searching for Records</h3>
</div>
</div>
</div>
<p>
You can use cursors to search for database records. You can search based
on just a key, or you can search based on both the key and the data.
You can also perform partial matches if your database supports sorted
duplicate sets. In all cases, the key and data parameters of these
methods are filled with the key and data values of the database record
to which the cursor is positioned as a result of the search.
</p>
<p>
Also, if the search fails, then cursor's state is left unchanged
and
<code class="literal">OperationStatus.NOTFOUND</code>
is returned.
</p>
<p>
The following <code class="classname">Cursor</code> methods allow you to
perform database searches:
</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>
<code class="methodname">Cursor.getSearchKey()</code>
</p>
<p>
Moves the cursor to the first record in the database with
the specified key.
</p>
</li>
<li>
<p>
<code class="methodname">Cursor.getSearchKeyRange()</code>
</p>
<p>
<span>Moves the cursor</span>
to the first record in the database whose
key is greater than or equal to the specified key. This comparison
is determined by the
<span>comparator</span>
that you provide for the database. If no
<span>comparator</span>
is provided, then the default
<span> unsigned byte-by-byte </span>
lexicographical sorting is used.
</p>
<p>
For example, suppose you have database records that use the
following
<span>Strings</span>
as keys:
</p>
<pre class="programlisting">Alabama
Alaska
Arizona</pre>
<p>
Then providing a search key of <code class="literal">Alaska</code> moves the
cursor to the second key noted above. Providing a key of
<code class="literal">Al</code> moves the cursor to the first key (<code class="literal">Alabama</code>), providing
a search key of <code class="literal">Alas</code> moves the cursor to the second key
(<code class="literal">Alaska</code>), and providing a key of <code class="literal">Ar</code> moves the
cursor to the last key (<code class="literal">Arizona</code>).
</p>
</li>
<li>
<p>
<code class="methodname">Cursor.getSearchBoth()</code>
</p>
<p>
Moves the cursor to the first record in the database that uses
the specified key and data.
</p>
</li>
<li>
<p>
<code class="methodname">Cursor.getSearchBothRange()</code>
</p>
<p>
Moves the cursor to the first record in the database whose key matches the specified
key and whose data is
greater than or equal to the specified data. If the database supports
duplicate records, then on matching the key, the cursor is moved to
the duplicate record with the smallest data that is greater than or
equal to the specified data.
</p>
<p>
For example,
<span>suppose you have</span>
database records that use the following key/data pairs:
</p>
<pre class="programlisting">Alabama/Athens
Alabama/Florence
Alaska/Anchorage
Alaska/Fairbanks
Arizona/Avondale
Arizona/Florence </pre>
<p>then providing:</p>
<div class="informaltable">
<table border="1" width="80%">
<colgroup>
<col />
<col />
<col />
</colgroup>
<thead>
<tr>
<th>a search key of ...</th>
<th>and a search data of ...</th>
<th>moves the cursor to ...</th>
</tr>
</thead>
<tbody>
<tr>
<td>Alaska</td>
<td>Fa</td>
<td>Alaska/Fairbanks</td>
</tr>
<tr>
<td>Arizona</td>
<td>Fl</td>
<td>Arizona/Florence</td>
</tr>
<tr>
<td>Alaska</td>
<td>An</td>
<td>Alaska/Anchorage</td>
</tr>
</tbody>
</table>
</div>
</li>
</ul>
</div>
<p>
For example, assuming a database containing sorted duplicate records of
U.S. States/U.S Cities key/data pairs (both as
<span>Strings),</span>
then the following code fragment can be used to position the cursor
to any record in the database and print its key/data values:
<span>
</span>
</p>
<a id="je_cursor5"></a>
<pre class="programlisting">package je.gettingStarted;
import com.sleepycat.je.Cursor;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.LockMode;
import com.sleepycat.je.OperationStatus;
...
// For this example, hard code the search key and data
String searchKey = "Alaska";
String searchData = "Fa";
Cursor cursor = null;
try {
...
// Database and environment open omitted for brevity
...
// Open the cursor.
cursor = myDatabase.openCursor(null, null);
DatabaseEntry theKey =
new DatabaseEntry(searchKey.getBytes("UTF-8"));
DatabaseEntry theData =
new DatabaseEntry(searchData.getBytes("UTF-8"));
// Open a cursor using a database handle
cursor = myDatabase.openCursor(null, null);
// Perform the search
OperationStatus retVal = cursor.getSearchBothRange(theKey, theData,
LockMode.DEFAULT);
// NOTFOUND is returned if a record cannot be found whose key
// matches the search key AND whose data begins with the search data.
if (retVal == OperationStatus.NOTFOUND) {
System.out.println(searchKey + "/" + searchData +
" not matched in database " +
myDatabase.getDatabaseName());
} else {
// Upon completing a search, the key and data DatabaseEntry
// parameters for getSearchBothRange() are populated with the
// key/data values of the found record.
String foundKey = new String(theKey.getData(), "UTF-8");
String foundData = new String(theData.getData(), "UTF-8");
System.out.println("Found record " + foundKey + "/" + foundData +
"for search key/data: " + searchKey +
"/" + searchData);
}
} catch (Exception e) {
// Exception handling goes here
} finally {
// Make sure to close the cursor
cursor.close();
}</pre>
</div>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="getdups"></a>Working with Duplicate Records</h3>
</div>
</div>
</div>
<p>
If your database supports duplicate records, then it can potentially
contain multiple records that share the same key.
<span>
Using normal database get operations, you can only ever obtain the
first such record in a set of duplicate records. To access subsequent
duplicates, use a cursor.
</span>
The following
<span><code class="methodname">Cursor</code> methods</span>
are interesting when working with databases that support duplicate records:
</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>
<span>
<code class="methodname">Cursor.getNext()</code>,
<code class="methodname">Cursor.getPrev()</code>
</span>
</p>
<p>
Shows the next/previous record in the database, regardless of
whether it is a duplicate of the current record. For an example of
using these methods, see <a class="xref" href="Positioning.html" title="Getting Records Using the Cursor">Getting Records Using the Cursor</a>.
</p>
</li>
<li>
<p>
<code class="methodname">Cursor.getSearchBothRange()</code>
</p>
<p>
Useful for seeking the cursor to a specific record, regardless of
whether it is a duplicate record. See <a class="xref" href="Positioning.html#cursorsearch" title="Searching for Records">Searching for Records</a> for more
information.
</p>
</li>
<li>
<p>
<span>
<code class="methodname">Cursor.getNextNoDup()</code>,
<code class="methodname">Cursor.getPrevNoDup()</code>
</span>
</p>
<p>
Gets the next/previous non-duplicate record in the database. This
allows you to skip over all the duplicates in a set of duplicate
records. If you call
<span><code class="methodname">Cursor.getPrevNoDup()</code>,</span>
then the cursor is positioned to the last record for the previous
key in the database. For example, if you have the following records
in your database:
</p>
<pre class="programlisting">Alabama/Athens
Alabama/Florence
Alaska/Anchorage
Alaska/Fairbanks
Arizona/Avondale
Arizona/Florence</pre>
<p>
and your cursor is positioned to <code class="literal">Alaska/Fairbanks</code>,
and you then call
<span><code class="methodname">Cursor.getPrevNoDup()</code>,</span>
then the cursor is positioned to Alabama/Florence. Similarly, if
you call
<span><code class="methodname">Cursor.getNextNoDup()</code>,</span>
then the cursor is positioned to the first record corresponding to
the next key in the database.
</p>
<p>
If there is no next/previous key in the database, then
<code class="literal">OperationStatus.NOTFOUND</code>
is returned, and the cursor is left unchanged.
</p>
</li>
<li>
<p>
<span>
<code class="methodname">Cursor.getNextDup()</code>,
<code class="methodname">Cursor.getPrevDup()</code>
</span>
</p>
<p>
Gets the
<span>next/previous</span>
record that shares the current key. If the
cursor is positioned at the last record in the duplicate set and
you call
<span><code class="methodname">Cursor.getNextDup()</code>,</span>
then
<code class="literal">OperationStatus.NOTFOUND</code>
is returned and the cursor is left unchanged.
<span>
Likewise, if you call
<code class="methodname">getPrevDup()</code> and the
cursor is positioned at the first record in the duplicate set, then
<code class="literal">OperationStatus.NOTFOUND</code> is returned and the
cursor is left unchanged.
</span>
</p>
</li>
<li>
<p>
<code class="methodname">Cursor.count()</code>
</p>
<p>Returns the total number of records that share the current key.</p>
</li>
</ul>
</div>
<p>
For example, the following code fragment positions a cursor to a key
<span>and, if the key contains duplicate records,
displays all the duplicates.</span>
<span>Note that the following code fragment assumes that the database contains
only String objects for the keys and data.</span>
</p>
<a id="je_cursor6"></a>
<pre class="programlisting">package je.gettingStarted;
import com.sleepycat.je.Cursor;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.LockMode;
import com.sleepycat.je.OperationStatus;
...
Cursor cursor = null;
try {
...
// Database and environment open omitted for brevity
...
// Create DatabaseEntry objects
// searchKey is some String.
DatabaseEntry theKey = new DatabaseEntry(searchKey.getBytes("UTF-8"));
DatabaseEntry theData = new DatabaseEntry();
// Open a cursor using a database handle
cursor = myDatabase.openCursor(null, null);
// Position the cursor
// Ignoring the return value for clarity
OperationStatus retVal = cursor.getSearchKey(theKey, theData,
LockMode.DEFAULT);
// Count the number of duplicates. If the count is greater than 1,
// print the duplicates.
if (cursor.count() &gt; 1) {
while (retVal == OperationStatus.SUCCESS) {
String keyString = new String(theKey.getData(), "UTF-8");
String dataString = new String(theData.getData(), "UTF-8");
System.out.println("Key | Data : " + keyString + " | " +
dataString + "");
retVal = cursor.getNextDup(theKey, theData, LockMode.DEFAULT);
}
}
} catch (Exception e) {
// Exception handling goes here
} finally {
// Make sure to close the cursor
cursor.close();
}</pre>
</div>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="Cursors.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="Cursors.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="PutEntryWCursor.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Chapter 9. Using Cursors </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Putting Records Using Cursors</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,186 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Putting Records Using Cursors</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="Cursors.html" title="Chapter 9. Using Cursors" />
<link rel="prev" href="Positioning.html" title="Getting Records Using the Cursor" />
<link rel="next" href="DeleteEntryWCursor.html" title="Deleting Records Using Cursors" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Putting Records Using Cursors</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="Positioning.html">Prev</a> </td>
<th width="60%" align="center">Chapter 9. Using Cursors</th>
<td width="20%" align="right"> <a accesskey="n" href="DeleteEntryWCursor.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="PutEntryWCursor"></a>Putting Records Using Cursors</h2>
</div>
</div>
</div>
<p>
You can use cursors to put records into the database. JE's behavior
when putting records into the database differs depending on whether the
database supports duplicate records. If duplicates are allowed, its
behavior also differs depending on whether a comparator is provided for
the database. (Comparators are described in
<a class="xref" href="comparator.html" title="Using Comparators">Using Comparators</a>).
</p>
<p>
Note that when putting records to the database using a cursor, the
cursor is positioned at the record you inserted.
</p>
<p>
You can use the following methods to put records to the database:
</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>
<code class="methodname">Cursor.put()</code>
</p>
<p>
If the provided key does not exist in the database,
then the order that the record is put into the database
is determined by the BTree (key) comparator in use by the database.
</p>
<p>
If the provided key already exists in the database, and the database
does not support sorted duplicates, then the existing record data is
replaced with the data provided on this method.
</p>
<p>
If the provided key already exists in the database, and the database
does support sorted duplicates, then the order that the record is
inserted into the database is determined by the duplicate comparator
in use by the database.
</p>
<p>
Note that a version of this method exists which allows you to
specify a Time to Live value for the record that you are
inserting. See <a class="xref" href="timetolive.html" title="Using Time to Live">Using Time to Live</a>
for more information.
</p>
</li>
<li>
<p>
<code class="methodname">Cursor.putNoDupData()</code>
</p>
<p>
If the provided key <span>and data</span> already exists
in the database, then this method returns
<code class="literal">OperationStatus.KEYEXIST</code>.
</p>
<p>
If the key does not exist, then the order that the record is put into the database
is determined by the
<span>
BTree (key) comparator in use by the database.
</span>
</p>
<span></span>
</li>
<li>
<p>
<code class="methodname">Cursor.putNoOverwrite()</code>
</p>
<p>
If the provided key already exists
in the database, then this method returns
<code class="literal">OperationStatus.KEYEXIST</code>.
</p>
<p>
If the key does not exist, then the order that the record is put into the database
is determined by the BTree (key) comparator in use by the database.
</p>
</li>
</ul>
</div>
<p>For example:</p>
<a id="je_cursor7"></a>
<pre class="programlisting">package je.gettingStarted;
import com.sleepycat.je.Cursor;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.OperationStatus;
...
// Create the data to put into the database
String key1str = "My first string";
String data1str = "My first data";
String key2str = "My second string";
String data2str = "My second data";
String data3str = "My third data";
Cursor cursor = null;
try {
...
// Database and environment open omitted for brevity
...
DatabaseEntry key1 = new DatabaseEntry(key1str.getBytes("UTF-8"));
DatabaseEntry data1 = new DatabaseEntry(data1str.getBytes("UTF-8"));
DatabaseEntry key2 = new DatabaseEntry(key2str.getBytes("UTF-8"));
DatabaseEntry data2 = new DatabaseEntry(data2str.getBytes("UTF-8"));
DatabaseEntry data3 = new DatabaseEntry(data3str.getBytes("UTF-8"));
// Open a cursor using a database handle
cursor = myDatabase.openCursor(null, null);
// Assuming an empty database.
OperationStatus retVal = cursor.put(key1, data1); // SUCCESS
retVal = cursor.put(key2, data2); // SUCCESS
retVal = cursor.put(key2, data3); // SUCCESS if dups allowed,
// KEYEXIST if not.
} catch (Exception e) {
// Exception handling goes here
} finally {
// Make sure to close the cursor
cursor.close();
}</pre>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="Positioning.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="Cursors.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="DeleteEntryWCursor.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Getting Records Using the Cursor </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Deleting Records Using Cursors</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,123 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Replacing Records Using Cursors</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="Cursors.html" title="Chapter 9. Using Cursors" />
<link rel="prev" href="DeleteEntryWCursor.html" title="Deleting Records Using Cursors" />
<link rel="next" href="cursorUsage.html" title="Cursor Example" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Replacing Records Using Cursors</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="DeleteEntryWCursor.html">Prev</a> </td>
<th width="60%" align="center">Chapter 9. Using Cursors</th>
<td width="20%" align="right"> <a accesskey="n" href="cursorUsage.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="ReplacingEntryWCursor"></a>Replacing Records Using Cursors</h2>
</div>
</div>
</div>
<p>
You replace the data for a database record by using
<span>
<code class="methodname">Cursor.putCurrent()</code>.
This method takes just one
argument — the data that you want to write to the current location in the
database.
</span>
</p>
<a id="je_cursor9"></a>
<pre class="programlisting">import com.sleepycat.je.Cursor;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.LockMode;
import com.sleepycat.je.OperationStatus;
...
Cursor cursor = null;
try {
...
// Database and environment open omitted for brevity
...
// Create DatabaseEntry objects
// searchKey is some String.
DatabaseEntry theKey = new DatabaseEntry(searchKey.getBytes("UTF-8"));
DatabaseEntry theData = new DatabaseEntry();
// Open a cursor using a database handle
cursor = myDatabase.openCursor(null, null);
// Position the cursor. Ignoring the return value for clarity
OperationStatus retVal = cursor.getSearchKey(theKey, theData,
LockMode.DEFAULT);
// Replacement data
String replaceStr = "My replacement string";
DatabaseEntry replacementData =
new DatabaseEntry(replaceStr.getBytes("UTF-8"));
cursor.putCurrent(replacementData);
} catch (Exception e) {
// Exception handling goes here
} finally {
// Make sure to close the cursor
cursor.close();
}</pre>
<p>
Note that this method cannot be used if the record that you are trying
to replace is a member of a duplicate set. This is because records must
be sorted by their data and replacement would violate that sort order.
</p>
<p>
<span>If</span>
you want to replace the data contained by a duplicate record,
delete the record and create a new record with the desired key and data.
</p>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="DeleteEntryWCursor.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="Cursors.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="cursorUsage.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Deleting Records Using Cursors </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Cursor Example</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,237 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Part III. Administering JE Applications</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="prev" href="indexusage.html" title="Secondary Database Example" />
<link rel="next" href="backuprestore.html" title="Chapter 11. Backing up and Restoring Berkeley DB Java Edition Applications" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Part III. Administering JE Applications</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="indexusage.html">Prev</a> </td>
<th width="60%" align="center"> </th>
<td width="20%" align="right"> <a accesskey="n" href="backuprestore.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="part" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h1 class="title"><a id="admin"></a>Part III. Administering JE Applications</h1>
</div>
</div>
</div>
<div class="partintro" lang="en" xml:lang="en">
<div></div>
<p>
This section discusses concepts and mechanisms
useful for the administration of any JE
application, regardless of the API used to build
that application.
</p>
<div class="toc">
<p>
<b>Table of Contents</b>
</p>
<dl>
<dt>
<span class="chapter">
<a href="backuprestore.html">11. Backing up and Restoring Berkeley DB Java Edition Applications</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect1">
<a href="backuprestore.html#databaselogs">Databases and Log Files</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect2">
<a href="backuprestore.html#lognames">Log File Overview</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="backuprestore.html#logcleaning">Cleaning the Log Files</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="backuprestore.html#btree">The BTree</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="backuprestore.html#syncs">Database Modifications and Syncs</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="backuprestore.html#normalrecovery">Normal Recovery</a>
</span>
</dt>
</dl>
</dd>
<dt>
<span class="sect1">
<a href="backup.html">Performing Backups</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect2">
<a href="backup.html#partialBackup">Performing a Hot Backup</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="backup.html#completeBackup">Performing an Offline Backup</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="backup.html#dbbackuphelper">Using the DbBackup Helper Class</a>
</span>
</dt>
</dl>
</dd>
<dt>
<span class="sect1">
<a href="catastrophicrecovery.html">Performing Catastrophic Recovery</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="hotfailover.html">Hot Standby</a>
</span>
</dt>
</dl>
</dd>
<dt>
<span class="chapter">
<a href="administration.html">12. Administering Berkeley DB Java Edition Applications</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect1">
<a href="administration.html#propertyfile">The JE Properties File</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="backgroundthreads.html">Managing the Background Threads</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect2">
<a href="backgroundthreads.html#cleaner">The Cleaner Thread</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="backgroundthreads.html#checkpointer">The Checkpointer Thread</a>
</span>
</dt>
</dl>
</dd>
<dt>
<span class="sect1">
<a href="cachesize.html">Sizing the Cache</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="diskthreshold.html">Setting Disk Thresholds</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="commandlinetools.html">The Command Line Tools</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect2">
<a href="commandlinetools.html#DbDump">DbDump</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="commandlinetools.html#DbLoad">DbLoad</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="commandlinetools.html#DbVerify">DbVerify</a>
</span>
</dt>
</dl>
</dd>
<dt>
<span class="sect1">
<a href="managelogging.html">Logging</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect2">
<a href="managelogging.html#logginglevels">Managing Logging Levels</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="managelogging.html#handlerlevels">Managing Handler Levels</a>
</span>
</dt>
</dl>
</dd>
</dl>
</dd>
</dl>
</div>
</div>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="indexusage.html">Prev</a> </td>
<td width="20%" align="center"> </td>
<td width="40%" align="right"> <a accesskey="n" href="backuprestore.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Secondary Database Example </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Chapter 11. Backing up and Restoring Berkeley DB Java Edition Applications</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,181 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Chapter 12. Administering Berkeley DB Java Edition Applications</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="admin.html" title="Part III. Administering JE Applications" />
<link rel="prev" href="hotfailover.html" title="Hot Standby" />
<link rel="next" href="backgroundthreads.html" title="Managing the Background Threads" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Chapter 12. Administering Berkeley DB Java Edition Applications</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="hotfailover.html">Prev</a> </td>
<th width="60%" align="center">Part III. Administering JE Applications</th>
<td width="20%" align="right"> <a accesskey="n" href="backgroundthreads.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="chapter" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title"><a id="administration"></a>Chapter 12. Administering Berkeley DB Java Edition Applications</h2>
</div>
</div>
</div>
<div class="toc">
<p>
<b>Table of Contents</b>
</p>
<dl>
<dt>
<span class="sect1">
<a href="administration.html#propertyfile">The JE Properties File</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="backgroundthreads.html">Managing the Background Threads</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect2">
<a href="backgroundthreads.html#cleaner">The Cleaner Thread</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="backgroundthreads.html#checkpointer">The Checkpointer Thread</a>
</span>
</dt>
</dl>
</dd>
<dt>
<span class="sect1">
<a href="cachesize.html">Sizing the Cache</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="diskthreshold.html">Setting Disk Thresholds</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="commandlinetools.html">The Command Line Tools</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect2">
<a href="commandlinetools.html#DbDump">DbDump</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="commandlinetools.html#DbLoad">DbLoad</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="commandlinetools.html#DbVerify">DbVerify</a>
</span>
</dt>
</dl>
</dd>
<dt>
<span class="sect1">
<a href="managelogging.html">Logging</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect2">
<a href="managelogging.html#logginglevels">Managing Logging Levels</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="managelogging.html#handlerlevels">Managing Handler Levels</a>
</span>
</dt>
</dl>
</dd>
</dl>
</div>
<p>
There are a series of tools and parameters of interest to the
administrator of a Berkeley DB Java Edition database.
These tools and parameters are useful for tuning your
JE database's behavior once it is in a production
setting, and they are described here. This chapter, however, does not describe backing up and restoring your
JE databases. See
<a class="xref" href="backuprestore.html" title="Chapter 11. Backing up and Restoring Berkeley DB Java Edition Applications">Backing up and Restoring Berkeley DB Java Edition Applications</a> for information on how to perform those procedures.
</p>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="propertyfile"></a>The JE Properties File</h2>
</div>
</div>
</div>
<p>
JE applications can be controlled through a
Java properties file. This file must be placed in your environment home directory and it must be named
<code class="filename">je.properties</code>.
</p>
<p>
The parameters set in this file take precedence over the configuration behavior coded into the
JE application by your application developers.
</p>
<p>
Usually you will use this file to control the behavior of JE's background threads, and to control the size of your
in-memory cache. These topics, and the properties parameters related to them, are described in this chapter.
Beyond the properties described here, there are other properties identified throughout this manual that may be
of interest to you. However, the definitive identification of all
the property parameters available to you is described in the javadoc for the
<code class="classname">EnvironmentConfig</code> class. Each property has a
<code class="classname">String</code> constant in <code class="classname">EnvironmentConfig</code> that
describes its meaning, default value, and so forth.
</p>
</div>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="hotfailover.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="admin.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="backgroundthreads.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Hot Standby </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Managing the Background Threads</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,628 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>The JE Application</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="introduction.html" title="Chapter 1. Introduction to Berkeley DB Java Edition" />
<link rel="prev" href="introduction.html" title="Chapter 1. Introduction to Berkeley DB Java Edition" />
<link rel="next" href="restore.html" title="JE Backup and Restore" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">The JE Application</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="introduction.html">Prev</a> </td>
<th width="60%" align="center">Chapter 1. Introduction to Berkeley DB Java Edition </th>
<td width="20%" align="right"> <a accesskey="n" href="restore.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="applicationoverview"></a>The JE Application</h2>
</div>
</div>
</div>
<div class="toc">
<dl>
<dt>
<span class="sect2">
<a href="applicationoverview.html#dbIntro">Database Environments</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="applicationoverview.html#key-data">Key-Data Pairs</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="applicationoverview.html#storing-intro">Storing Data</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="applicationoverview.html#duplicatesintro">Duplicate Data</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="applicationoverview.html#replacedeleteIntro">Replacing and Deleting Entries</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="applicationoverview.html#secondary">Secondary Keys</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="applicationoverview.html#transactionIntro">Transactions</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="applicationoverview.html#resourcesIntro">JE Resources</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="applicationoverview.html#applicationConsiderations">
Application Considerations
</a>
</span>
</dt>
</dl>
</div>
<p>This section provides a brief overview to the major concepts and
operations that comprise a JE application. This section is concluded with a summary of the decisions that
you need to make when working with JE.</p>
<p>
Note that the core JE classes are all contained in the <code class="literal">com.sleepycat.je</code> package.
In addition, this book describes some classes that are found in <code class="literal">com.sleepycat.je.bind</code>.
The bind APIs are used for converting Java objects in and out of <code class="literal">byte</code> arrays.
</p>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="dbIntro"></a>Database Environments</h3>
</div>
</div>
</div>
<p>
Regardless of the JE API that you use, your data is
stored in databases. If you use the DPL, you do not manage
these databases directly; rather, they are managed for you by
the API. On the other hand, if you use the lower-level JE
APIs, then you must manage databases directly. This is not
difficult to do as it mostly involves opening and closing the
databases, giving them names, and so forth. See
<a class="xref" href="databases.html" title="Chapter 7. Databases">Databases</a>
for more
information.
</p>
<p>
That said, JE always requires you to use a
<span class="emphasis"><em>database environment</em></span>. Database
environments provide an unit of encapsulation for one or more
databases. Environments correspond to a directory location on
disk, and in them you will find all the files in use by JE.
Environments are also used to manage JE resources such as
transactions.
</p>
<p>
To use a database environment, it must first be created and then
opened. In order to create a database environment, the
directory location in which it resides must already exist.
</p>
<p>
You open a database environment by instantiating an
<code class="classname">Environment</code> object. Your
<code class="classname">Environment</code> instance is called
an <span class="emphasis"><em>environment handle</em></span>.
</p>
<p>
Once you have opened an environment, what you do with it
depends on the nature of your application; that is, the
JE API you are using and whether you are using advanced
features such as transactions. (See
<em class="citetitle">Berkeley DB, Java Edition Getting Started with Transaction Processing</em>
for details on using
transactions). However, at a minimum you will always have to
open your environment before you can access your data stored
in JE. Also, before you end your application you should
always close your environment.
</p>
<p>
Environments are described in greater detail in <a class="xref" href="env.html" title="Chapter 2. Database Environments">Database Environments</a>.
</p>
</div>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="key-data"></a>Key-Data Pairs</h3>
</div>
</div>
</div>
<p>
JE stores and retrieves data using
<span class="emphasis"><em>key-data pairs</em></span>. The
<span class="emphasis"><em>data</em></span> portion of this is the data
that you have decided to store in JE for future
retrieval. The <span class="emphasis"><em>key</em></span> is the
information that you want to use to look up your
stored data once it has been placed inside a JE
database.
</p>
<p>
For example, if you were building a database that
contained employee information, then the
<span class="emphasis"><em>data</em></span> portion is all of the
information that you want to store about the employees:
name, address, phone numbers, physical location, their
manager, and so forth.
</p>
<p>
The <span class="emphasis"><em>key</em></span>, however, is the way that
you look up any given employee. You can have more than
one key if you wish, but every record in your database must have a
primary key. If you are using the DPL, then this key must be unique; that is,
it must not be used multiple times in the database. However, if you are using
the base API, then this requirement is relaxed. See
<a class="xref" href="applicationoverview.html#duplicatesintro" title="Duplicate Data">Duplicate Data</a> for more
information.
</p>
<p>
For example, in the case of an employee database, you would probably use
something like the employee identification number as the primary key as this
uniquely identifies a given employee.
</p>
<p>
You can optionally also have secondary keys that represent indexes
into your database. These keys do not have to be unique
to a given record; in fact, they often are not. For
example, you might set up the employee's manager's name
as a secondary key so that it is easy to locate all
the employee's that work for a given manager.
</p>
</div>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="storing-intro"></a>Storing Data</h3>
</div>
</div>
</div>
<p>
How you manage your stored information differs
significantly, depending on which API you are using.
Both APIs ultimately are doing the same thing, but the
DPL hides a lot of the details from you.
</p>
<div class="sect3" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h4 class="title"><a id="dplstore"></a>Storing Data in the DPL</h4>
</div>
</div>
</div>
<p>
The DPL is used to store Java objects in an
underlying series of databases. These databases are
accessed using an <code class="classname">EntityStore</code>
class object.
</p>
<p>
To use the DPL, you must decorate the classes you
want to store with Java annotations that identify them
as either an <span class="emphasis"><em>entity class</em></span> or a
<span class="emphasis"><em>persistent class</em></span>.
</p>
<p>
Entity classes are classes that have a primary key, and
optionally one or more secondary keys. That is, these
are the classes that you will save and retrieve directly
using the DPL. You identify an entity class using the
<code class="literal">@Entity</code> java annotation.
</p>
<p>
Persistent classes are classes used by entity classes.
They do not have primary or secondary indices used for
object retrieval. Rather, they are stored or retrieved
when an entity class makes direct use of them. You
identify an persistent class using the
<code class="literal">@Persistent</code> java annotation.
</p>
<p>
The primary key for an object is obtained from one of the class' data members.
You identify which data member to use as the primary key using the
<code class="literal">@PrimaryKey</code> java annotation.
</p>
<p>
Note that all non-transient instance fields of a
persistent class, as well as its superclasses and
subclasses, are persistent. Static and transient fields
are not persistent. The persistent fields of a class
may be private, package-private (default access),
protected or public.
</p>
<p>
Also, simple Java types, such as
<code class="classname">java.lang.String</code> and
<code class="classname">java.util.Date</code>, are automatically handled as a
persistent class when you use them in an entity class;
you do not have to do anything special to cause these
simple Java objects to be stored in the
<code class="classname">EntityStore</code>.
</p>
</div>
<div class="sect3" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h4 class="title"><a id="lowlevelstore"></a>Storing Data using the Base API</h4>
</div>
</div>
</div>
<p>
When you are not using the DPL, both record keys and record data must be byte
arrays and are passed to and returned from JE using
<code class="classname">DatabaseEntry</code> instances.
<code class="classname">DatabaseEntry</code> only supports storage of Java byte arrays.
Complex objects must be marshaled using either Java serialization, or more
efficiently with the bind APIs provided with JE </p>
<p> Database
records and <code class="literal">byte</code> array conversion are described in <a class="xref" href="DBEntry.html" title="Chapter 8. Database Records">Database Records</a>.
</p>
<p>
You store records in a <code class="classname">Database</code> by calling one of the
put methods on a <code class="classname">Database</code> handle. JE
automatically determines the record's proper placement in the database's
internal B-Tree using whatever key and data comparison functions that are
available to it.
</p>
<p>
You can also retrieve, or get, records using the
<code class="classname">Database</code> handle. Gets are performed by providing the
key (and sometimes also the data) of the record that you want to retrieve.
</p>
<p>
You can also use cursors for database puts and gets. Cursors are essentially
a mechanism by which you can iterate over the records in the database. Like
databases and database environments, cursors must be opened and closed.
Cursors are managed using the <code class="classname">Cursor</code> class.
</p>
<p>
Databases are described in <a class="xref" href="databases.html" title="Chapter 7. Databases">Databases</a>. Cursors
are described in <a class="xref" href="Cursors.html" title="Chapter 9. Using Cursors">Using Cursors</a>.
</p>
</div>
</div>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="duplicatesintro"></a>Duplicate Data</h3>
</div>
</div>
</div>
<p>
If you are using the base API, then at creation time databases can be configured to
allow duplicate data. Remember that JE database records consist of a key/data
pair. <span class="emphasis"><em>Duplicate data</em></span>, then, occurs when two or more records have
identical keys, but different data. By default, a <code class="classname">Database</code> does
not allow duplicate data.
</p>
<p>
If your <code class="classname">Database </code> contains duplicate data, then a simple
database get based only on a key returns just the first record that uses that key. To
access all duplicate records for that key, you must use a cursor.
</p>
<p>
If you are using the DPL, then you can duplicate date using
secondary keys, but not by using the primary key. For more information, see
<a class="xref" href="getmultiple.html" title="Retrieving Multiple Objects">Retrieving Multiple Objects</a>.
</p>
</div>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="replacedeleteIntro"></a>Replacing and Deleting Entries</h3>
</div>
</div>
</div>
<p>
If you are using the DPL, then replacing a stored entity object simply consists of
retrieving it, updating it, then storing it again. To delete the object, use the
<code class="methodname">delete()</code> method that is available on either its primary or
secondary keys. If you use the <code class="methodname">delete()</code> method available on
the secondary key, then all objects referenced by that key are also deleted.
See <a class="xref" href="dpl_delete.html" title="Deleting Entity Objects">Deleting Entity Objects</a>
for more information.
</p>
<p>
If you are using the base API, then how you replace database records depends on whether
duplicate data is allowed in the database.
</p>
<p>
If duplicate data is not allowed in the database, then simply calling
<code class="methodname">Database.put()</code> with the appropriate key will cause any
existing record to be updated with the new data. Similarly, you can delete a record by
providing the appropriate key to the <code class="methodname">Database.delete()</code>
method.
</p>
<p>
If duplicate data is allowed in the database, then you must position a cursor to the
record that you want to update, and then perform the put operation using the cursor.
</p>
<p>
To delete records using the base API, you can use either <code class="methodname">Database.delete()</code> or
<code class="methodname">Cursor.delete()</code>. If duplicate data is not allowed in your
database, then these two method behave identically. However, if duplicates are allowed
in the database, then <code class="methodname">Database.delete()</code> deletes every record
that uses the provided key, while <code class="methodname">Cursor.delete()</code> deletes just
the record at which the cursor is currently positioned.
</p>
</div>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="secondary"></a>Secondary Keys</h3>
</div>
</div>
</div>
<p>
Secondary keys provide an alternative way to locate information stored in
JE, beyond that which is provided by the primary key. Frequently secondary
keys refer to more than one record in the database. In this way, you can find
all the cars that are green (if you are maintaining an automotive database) or
all the people with brown eyes (if you are maintaining a database about people).
In other words, secondary keys represent a index into your data.
</p>
<p>
How you create and maintain secondary keys differs significantly, depending on
whether you are using the DPL or the base API.
</p>
<div class="sect3" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h4 class="title"><a id="secondarydpl"></a>Using Secondaries with the DPL</h4>
</div>
</div>
</div>
<p>
Under the DPL, you declare a particular field to be a secondary key by
using the <code class="literal">@SecondaryKey</code> annotation. When you do this,
you must declare what kind of an index you are creating. For example,
you can declare a secondary key to be part of a
<code class="literal">ONE_TO_ONE</code> index, in which case the key is unique to
the object. Or you could declare the key to be
<code class="literal">MANY_TO_ONE</code>, in which case the key can be used for
multiple objects in the data store.
</p>
<p>
Once you have identified secondary keys for a class, you can access
those keys by using the <code class="methodname">EntityStore.getSecondaryIndex()</code>
method.
</p>
<p>
For more information, see <a class="xref" href="dplindexcreate.html#dplsecondaryidxdecl" title="Declaring Secondary Indexes">Declaring Secondary Indexes</a>.
</p>
</div>
<div class="sect3" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h4 class="title"><a id="secondarybaseapi"></a>Using Secondaries with the Base API.</h4>
</div>
</div>
</div>
<p>
When you are using the base API, you create and maintain secondary keys using a
special type of a database, called a <span class="emphasis"><em>secondary database</em></span>.
When you are using secondary databases, the database that holds the data you are
indexing is called the <span class="emphasis"><em>primary database</em></span>.
</p>
<p>
You create a secondary database by opening it and associating it with an
existing primary database. You must also provide a class that generates the
secondary's keys (that is, the index) from primary records. Whenever a
record in the primary database is added or changed, JE uses this class
to determine what the secondary key should be.
</p>
<p>
When a primary record is created, modified, or deleted, JE automatically
updates the secondary database(s) for you as is appropriate for the
operation performed on the primary.
</p>
<p>
You manage secondary databases using the
<code class="classname">SecondaryDatabase</code> class. You identify how to create keys
for your secondary databases by supplying an instance of a class that implements
the <code class="classname">SecondaryKeyCreator</code> interface.
</p>
<p>
Secondary databases are described in <a class="xref" href="indexes.html" title="Chapter 10. Secondary Databases">Secondary Databases</a>.
</p>
</div>
</div>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="transactionIntro"></a>Transactions</h3>
</div>
</div>
</div>
<p>
Transactions provide a high level of safety for your JE operations by allowing
you to manage one or more operations as if they were a single unit of work.
Transactions provide your JE operations with recoverability, atomicity, and
isolation.
</p>
<p>
Transactions provide recoverability by allowing JE to undo any
transactional-protected operations that may have been in progress at the time of an
application or system failure.
</p>
<p>
Transactions provide atomicity by allowing you to group many operations into
a single unit of work. Either all operations succeed or none of them do. This means
that if one write operation fails for any reason, then all other writes contained
within that transaction also fail. This ensures that the database is never partially
updated as the result of an only partially successful chain of read/write operations.
</p>
<p>
Transactions provide isolation by ensuring that the transaction will never write to a
record that is currently in use (for either read or write) by another transaction.
Similarly, any record to which the transaction has written can not be read outside of
the transaction until the transaction ends. Note that this is only the default
behavior; you can configure your <code class="classname">Database</code>,
<code class="classname">Cursor</code>, or <code class="classname">Transaction</code> handle to relax
its isolation guarantees.
</p>
<p>
Essentially, transactional isolation provides a transaction with the same unmodified view of the
database that it would have received had the operations been performed in a single-threaded application.
</p>
<p>
Transactions may be long or short lived, they can encompass as many
operations as you want, and (if using the base API) they can span databases
so long as all participating databases reside in the same environment.
</p>
<p>
Transaction usage results in a performance penalty for the application because they
generally require more disk I/O than do non-transactional operations. Therefore, while
most applications will use transactions for JE writes, their usage is optional.
In particular, processes that are performing read-only operations
might not use transactions. Also, applications that use JE for an easily
recreated cache might also choose to avoid transactions.
</p>
<p>
Using transactions with your JE applications is described in detail in the
<em class="citetitle">Berkeley DB, Java Edition Getting Started with Transaction Processing</em> guide.
</p>
</div>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="resourcesIntro"></a>JE Resources</h3>
</div>
</div>
</div>
<p>
JE has some internal resources that you may want to manage. Most important of these is the in-memory cache.
You should carefully consider how large the JE cache needs to be. If you set this number too low, JE will
perform potentially unnecessary disk I/O which will result in a performance hit. If you set it too high, then
you are potentially wasting RAM that could be put to better purposes.
</p>
<p>
Note that the size that you configure for the in-memory cache is a maximum size. At application startup, the
cache starts out fairly small (only about 7% of the maximum allowed size for the cache). It then grows as is
required by your application's database operations. Also, the cache is not pinned in memory it can be
paged out by your operating system's virtual memory system.
</p>
<p>
Beyond the cache, JE uses several background threads to clean
the JE log files, to compress the database by removing unneeded
subtrees, and to flush database changes seen in the cache to the backing data files. For the
majority of JE applications, the default behavior for the background threads should be acceptable and you
will not need to manage their behavior. Note that background threads are started no more than once per
process upon environment open.
</p>
<p>
For more information on sizing the cache and on the background threads, see <a class="xref" href="administration.html" title="Chapter 12. Administering Berkeley DB Java Edition Applications">Administering Berkeley DB Java Edition Applications</a>.
</p>
</div>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="applicationConsiderations"></a>
Application Considerations
</h3>
</div>
</div>
</div>
<p>When building your JE application, be sure to think about the following things:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>What data do you want to store? What is best used for the
primary key? What is the best representation for primary record data?
If you are using the base API, think about the most efficient way to move your keys and data in and
out of byte arrays. See <a class="xref" href="DBEntry.html" title="Chapter 8. Database Records">Database Records</a> for more information.</p>
</li>
<li>
<p>Does the nature of your data require duplicate record support?
Remember that duplicate support can be configured only if you are using the base
API, and then only at database
creation time. See <a class="xref" href="databases.html#DBOpen" title="Opening Databases">Opening Databases</a> for more information.</p>
<p>If you are supporting duplicate records, you may also need to think
about duplicate comparators (not just key comparators). See
<a class="xref" href="comparator.html" title="Using Comparators">Using Comparators</a> for more information.</p>
</li>
<li>
<p>What secondary indexes do you need? How can you compute your secondary indexes based on the data and
keys stored in your primary database?
Indexes are described in <a class="xref" href="indexes.html" title="Chapter 10. Secondary Databases">Secondary Databases</a>.</p>
</li>
<li>
<p>What cache size do you need? See
<a class="xref" href="cachesize.html" title="Sizing the Cache">Sizing the Cache</a> for information on how to size your cache.</p>
</li>
<li>
<p>Does your application require transactions (most will).
Transactions are described in the
<em class="citetitle">Berkeley DB, Java Edition Getting Started with Transaction Processing</em> guide.
</p>
</li>
</ul>
</div>
</div>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="introduction.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="introduction.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="restore.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Chapter 1. Introduction to Berkeley DB Java Edition  </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> JE Backup and Restore</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,187 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Managing the Background Threads</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="administration.html" title="Chapter 12. Administering Berkeley DB Java Edition Applications" />
<link rel="prev" href="administration.html" title="Chapter 12. Administering Berkeley DB Java Edition Applications" />
<link rel="next" href="cachesize.html" title="Sizing the Cache" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Managing the Background Threads</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="administration.html">Prev</a> </td>
<th width="60%" align="center">Chapter 12. Administering Berkeley DB Java Edition Applications</th>
<td width="20%" align="right"> <a accesskey="n" href="cachesize.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="backgroundthreads"></a>Managing the Background Threads</h2>
</div>
</div>
</div>
<div class="toc">
<dl>
<dt>
<span class="sect2">
<a href="backgroundthreads.html#cleaner">The Cleaner Thread</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="backgroundthreads.html#checkpointer">The Checkpointer Thread</a>
</span>
</dt>
</dl>
</div>
<p>
JE uses some background threads to keep your database resources within pre-configured limits. If they are
going to run, the background threads are started once per application per process. That is, if your application
opens the same environment multiple times, the background threads will be started just once for that process.
See the following list for the default conditions that gate whether an individual thread is run. Note that you
can prevent a background thread from running by using the appropriate <code class="filename">je.properties</code>
parameter, but this is not recommended for production use and those parameters are not described here.
</p>
<p>
The background threads are:
</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>
Cleaner thread.
</p>
<p>
Responsible for cleaning and deleting unused log files. See <a class="xref" href="backgroundthreads.html#cleaner" title="The Cleaner Thread">The Cleaner Thread</a> for more information.
</p>
<p>
This thread is run only if the environment is opened for write access.
</p>
</li>
<li>
<p>
Compressor thread.
</p>
<p>
Responsible for cleaning up the internal BTree as database records are deleted. The compressor thread
ensures that the BTree does not contain unused nodes. There is no need for you to manage the
compressor and so it is not described further in this manual.
</p>
<p>
This thread is run only if the environment is opened for write access.
</p>
</li>
<li>
<p>
Checkpointer thread.
</p>
<p>
Responsible for running checkpoints on your environment. See
<a class="xref" href="backgroundthreads.html#checkpointer" title="The Checkpointer Thread">The Checkpointer Thread</a> for more information.
</p>
<p>
This thread always runs.
</p>
</li>
</ul>
</div>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="cleaner"></a>The Cleaner Thread</h3>
</div>
</div>
</div>
<p>
The cleaner thread is responsible for cleaning, or compacting, your log files for you.
Log file cleaning is described in <a class="xref" href="backuprestore.html#logcleaning" title="Cleaning the Log Files">Cleaning the Log Files</a>.
</p>
<p>
The following two properties may be of interest to you when managing the cleaner thread:
</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>
<code class="literal">je.cleaner.minUtilization</code>
</p>
<p>
Identifies the percentage of the log file space that must be used for utilized records. If the
percentage of log file space used by utilized records is too low, then the cleaner removes
obsolete records until this threshold is reached. Default is 50%.
</p>
</li>
<li>
<p>
<code class="literal">je.cleaner.expunge</code>
</p>
<p>
Identifies the cleaner's behavior in the event that it is able to remove a log file. If
<code class="literal">true</code>, the log files that have been cleaned are deleted from the file system. If
<code class="literal">false</code>, the log files that have been cleaned are renamed from
<code class="literal">NNNNNNNN.jdb</code> to <code class="literal">NNNNNNNN.del</code>. You are then responsible for
deleting the renamed files.
</p>
</li>
</ul>
</div>
<p>
Note that the cleaner thread runs only if the environment is opened for write access. Also, be aware that
the cleaner is not guaranteed to finish running before the environment is closed, which can result in
unexpectedly large log files. See
<a class="xref" href="envclose.html" title="Closing Database Environments">Closing Database Environments</a> for more information.
</p>
</div>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="checkpointer"></a>The Checkpointer Thread</h3>
</div>
</div>
</div>
<p>
Automatically runs checkpoints. Checkpoints and the administration of this thread are described in
the <em class="citetitle">Berkeley DB, Java Edition Getting Started with Transaction Processing</em> guide.
</p>
</div>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="administration.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="administration.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="cachesize.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Chapter 12. Administering Berkeley DB Java Edition Applications </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Sizing the Cache</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,291 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Performing Backups</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="backuprestore.html" title="Chapter 11. Backing up and Restoring Berkeley DB Java Edition Applications" />
<link rel="prev" href="backuprestore.html" title="Chapter 11. Backing up and Restoring Berkeley DB Java Edition Applications" />
<link rel="next" href="catastrophicrecovery.html" title="Performing Catastrophic Recovery" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Performing Backups</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="backuprestore.html">Prev</a> </td>
<th width="60%" align="center">Chapter 11. Backing up and Restoring Berkeley DB Java Edition Applications</th>
<td width="20%" align="right"> <a accesskey="n" href="catastrophicrecovery.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="backup"></a>Performing Backups</h2>
</div>
</div>
</div>
<div class="toc">
<dl>
<dt>
<span class="sect2">
<a href="backup.html#partialBackup">Performing a Hot Backup</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="backup.html#completeBackup">Performing an Offline Backup</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="backup.html#dbbackuphelper">Using the DbBackup Helper Class</a>
</span>
</dt>
</dl>
</div>
<p>
This section describes how to backup your JE database(s) such that catastrophic recovery is possible for
non-transactional applications. Note that this same material is repeated in the
<em class="citetitle">Berkeley DB, Java Edition Getting Started with Transaction Processing</em>
guide, but for transactional applications. If you are writing transactional
applications, you may want to skip the rest of this chapter and go straight to that book.
</p>
<p>
To backup your database, you can either take a hot backup or an offline backup. A hot
backup is performed while database write operations are in progress.
</p>
<p>
Do not confuse hot and offline backups with the concept of a full and incremental backup. Both a
hot and an offline backup are full backups you back up the entire database. The only difference
between them is how much of the contents of the in-memory cache are contained in them. On the other hand,
an incremental backup is a backup of just those log files modified or created since the time of the last
backup. Most backup software
is capable of performing both full and incremental backups for you.
</p>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="partialBackup"></a>Performing a Hot Backup</h3>
</div>
</div>
</div>
<p>
To perform a hot backup of your JE databases, copy all log files
(<code class="filename">*.jdb</code> files) from your environment directory to
your archival location or backup media. The files must be copied
in alphabetical order (numerical in effect). You do not have to
stop any database operations in order to do this.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;">
<h3 class="title">Note</h3>
<p>
If you are using subdirectories to store your log files, then you must backup
the subdirectories, making sure to keep log files in the subdirectory in which
JE placed them. For information on using subdirectories to store your log
files, see <a class="xref" href="env.html#multisubdir" title="Multiple Environment Subdirectories">Multiple Environment Subdirectories</a>.
</p>
</div>
<p>
To make this process a bit easier, you may want to make use of the
<code class="classname">DbBackup</code> helper class. See
<a class="xref" href="backup.html#dbbackuphelper" title="Using the DbBackup Helper Class">Using the DbBackup Helper Class</a>
for details.
</p>
<p>
Note that any modifications made to the database since the time of the last
environment sync are not guaranteed to be contained in these log files. In this
case, you may want to consider running an offline backup in order to guarantee the
availability of all modifications made to your database.
</p>
</div>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="completeBackup"></a>Performing an Offline Backup</h3>
</div>
</div>
</div>
<p>
An offline backup guarantees that you have captured the database in its entirety, including all contents
of your in-memory cache, at the moment that the
backup was taken. To do this, you must make sure that no write operations are in progress and all
database modifications have been written to your log files
on disk. To obtain an offline backup:
</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>
Stop writing your databases.
</p>
</li>
<li>
<p>
Run <code class="methodname">Environment.sync()</code> so as to
ensure that all database modifications are written to disk. Note that cleanly closing your
environment will also ensure that all database modifications are written to disk.
</p>
</li>
<li>
<p>
Copy all log files (<code class="filename">*.jdb</code>) from your environment
directory to your archival location or backup media. To make this process a
bit easier, you may want to make use of the <code class="classname">DbBackup</code>
helper class. See the next section for details.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;">
<h3 class="title">Note</h3>
<p>
If you are using subdirectories to store your log files, then you must backup
the subdirectories, making sure to keep log files in the subdirectory in which
JE placed them. For information on using subdirectories to store your log
files, see <a class="xref" href="env.html#multisubdir" title="Multiple Environment Subdirectories">Multiple Environment Subdirectories</a>.
</p>
</div>
</li>
</ol>
</div>
<p>
You can now resume normal database operations.
</p>
</div>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="dbbackuphelper"></a>Using the DbBackup Helper Class</h3>
</div>
</div>
</div>
<p>
In order to simplify backup operations, JE
provides the <code class="classname">DbBackup</code> helper
class. This class stops and restarts JE background activity
in an open environment. It also lets the application create a
backup which can support restoring the environment to
a specific point in time.
</p>
<p>
Because you do not have to stop JE write activity
in order to take a backup, it is usually necessary to
examine your log files twice before you decide that
your backup is complete. This is because JE may
create a new log file while you are running your
backup. A second pass over your log files allows you to
ensure that no new files have been created and so you
can declare your backup complete.
</p>
<p>
For example:
</p>
<pre class="programlisting"> time files in activity
environment
t0 000000001.jdb Backup starts copying file 1
000000003.jdb
000000004.jdb
t1 000000001.jdb JE log cleaner migrates portion of file 3 to
000000004.jdb newly created file 5 and deletes file 3.
000000005.jdb Backup finishes file 1, starts copying file 4.
Backup MUST include file 5 for a consistent
backup!
t2 000000001.jdb Backup finishes copying file 4, starts and
000000004.jdb finishes file 5, has caught up. Backup ends.
000000005.jdb
</pre>
<p>
<code class="classname">DbBackup</code> works around this
problem by defining the set of files that must be
copied for each backup operation, and freezes all
changes to those files. The application can copy that
defined set of files and finish operation without
checking for the ongoing creation of new files. Also,
there will be no need to check for a newer version of
the last file on the next backup.
</p>
<p>
In the example above, if <code class="classname">DbBackup</code> was used at t0,
the application would only have to copy files 1, 3 and
4 to back up. On a subsequent backup, the application
could start its copying at file 5. There would be no
need to check for a newer version of file 4.
</p>
<p>
The following code fragment illustrates this class' usage.
See the <code class="classname">DbBackup</code> javadoc for additional
examples and more information on incremental backups.
</p>
<pre class="programlisting">package je.gettingStarted;
...
import com.sleepycat.je.util.DbBackup;
...
// Find the file number of the last file in the previous backup
// persistently, by either checking the backup archive, or saving
// state in a persistent file.
long lastFileCopiedInPrevBackup = ...
Environment env = new Environment(...);
DbBackup backupHelper = new DbBackup(env, lastFileCopiedInPrevBackup);
// Start backup, find out what needs to be copied.
// If multiple environment subdirectories are in use,
// the getLogFilesInBackupSet returns the log file
// name prefixed with the dataNNN/ directory in which
// it resides.
backupHelper.startBackup();
try {
String[] filesForBackup = backupHelper.getLogFilesInBackupSet();
// Copy the files to archival storage.
myApplicationCopyMethod(filesForBackup)
// Update our knowlege of the last file saved in the backup set,
// so we can copy less on the next backup
lastFileCopiedInPrevBackup = backupHelper.getLastFileInBackupSet();
myApplicationSaveLastFile(lastFileCopiedInBackupSet);
}
finally {
// Remember to exit backup mode, or all log files won't be cleaned
// and disk usage will bloat.
backupHelper.endBackup();
} </pre>
</div>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="backuprestore.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="backuprestore.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="catastrophicrecovery.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Chapter 11. Backing up and Restoring Berkeley DB Java Edition Applications </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Performing Catastrophic Recovery</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,355 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Chapter 11. Backing up and Restoring Berkeley DB Java Edition Applications</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="admin.html" title="Part III. Administering JE Applications" />
<link rel="prev" href="admin.html" title="Part III. Administering JE Applications" />
<link rel="next" href="backup.html" title="Performing Backups" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Chapter 11. Backing up and Restoring Berkeley DB Java Edition Applications</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="admin.html">Prev</a> </td>
<th width="60%" align="center">Part III. Administering JE Applications</th>
<td width="20%" align="right"> <a accesskey="n" href="backup.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="chapter" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title"><a id="backuprestore"></a>Chapter 11. Backing up and Restoring Berkeley DB Java Edition Applications</h2>
</div>
</div>
</div>
<div class="toc">
<p>
<b>Table of Contents</b>
</p>
<dl>
<dt>
<span class="sect1">
<a href="backuprestore.html#databaselogs">Databases and Log Files</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect2">
<a href="backuprestore.html#lognames">Log File Overview</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="backuprestore.html#logcleaning">Cleaning the Log Files</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="backuprestore.html#btree">The BTree</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="backuprestore.html#syncs">Database Modifications and Syncs</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="backuprestore.html#normalrecovery">Normal Recovery</a>
</span>
</dt>
</dl>
</dd>
<dt>
<span class="sect1">
<a href="backup.html">Performing Backups</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect2">
<a href="backup.html#partialBackup">Performing a Hot Backup</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="backup.html#completeBackup">Performing an Offline Backup</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="backup.html#dbbackuphelper">Using the DbBackup Helper Class</a>
</span>
</dt>
</dl>
</dd>
<dt>
<span class="sect1">
<a href="catastrophicrecovery.html">Performing Catastrophic Recovery</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="hotfailover.html">Hot Standby</a>
</span>
</dt>
</dl>
</div>
<p>
Fundamentally, you backup your databases by copying JE log files off to a safe storage location. To restore
your database from a backup, you copy those files to an appropriate directory on disk and reopen your JE
application
</p>
<p>
Beyond these simple activities, there are some differing backup strategies that you may want to consider. These
topics are described in this chapter.
</p>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="databaselogs"></a>Databases and Log Files</h2>
</div>
</div>
</div>
<div class="toc">
<dl>
<dt>
<span class="sect2">
<a href="backuprestore.html#lognames">Log File Overview</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="backuprestore.html#logcleaning">Cleaning the Log Files</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="backuprestore.html#btree">The BTree</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="backuprestore.html#syncs">Database Modifications and Syncs</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="backuprestore.html#normalrecovery">Normal Recovery</a>
</span>
</dt>
</dl>
</div>
<p>
Before describing JE backup and restore, it is necessary to describe some of JE's internal workings. In
particular, a high-level understanding of JE log files and the in-memory cache is required. You also need
to understand a little about how JE is using its internal data structures in order to understand why
checkpoints and/or syncs are required.
</p>
<p>
You can skip this section so long as you understand that:
</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>
JE databases are stored in log files contained in your environment directory.
</p>
</li>
<li>
<p>
Every time a JE environment is opened, normal recovery is run.
</p>
</li>
<li>
<p>
For transactional applications, checkpoints should be run in order to bound normal recovery time.
Checkpoints are normally run by the checkpointer thread. Transactional applications and the
checkpointer thread are described in the
<em class="citetitle">Berkeley DB, Java Edition Getting Started with Transaction Processing</em> guide.
</p>
</li>
<li>
<p>
For non-transactional applications, environment syncs must be performed if you want to guarantee the
persistence of your database modifications. Environment syncs are manually performed by the
application developer. See <a class="xref" href="usingDbt.html#datapersist" title="Data Persistence">Data Persistence</a> for details.
</p>
</li>
</ul>
</div>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="lognames"></a>Log File Overview</h3>
</div>
</div>
</div>
<p>
Your JE database is stored on-disk in a series of log files.
JE uses no-overwrite log files, which is to say that JE only ever appends data to the end of a log
file. It will never delete or modify an existing log file record.
</p>
<p>
JE log files are named
<code class="literal">NNNNNNNN.jdb</code> where <code class="literal">NNNNNNNN</code> is an 8-digit hexadecimal number that
increases by 1 (starting from <code class="literal">00000000</code>) for each log file written to disk.
</p>
<p>
JE creates a new log file whenever the current log file has reached a pre-configured size (10000000
bytes by default). This size is controlled by the <code class="literal">je.log.fileMax</code> properties
parameter. See <a class="xref" href="administration.html#propertyfile" title="The JE Properties File">The JE Properties File</a> for information on setting
JE properties.
</p>
<p>
By default, log files are placed in the environment home directory. However, you can
cause JE to place log files in subdirectories within the environment home
directory. For more information, see
<a class="xref" href="env.html#multisubdir" title="Multiple Environment Subdirectories">Multiple Environment Subdirectories</a>.
</p>
</div>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="logcleaning"></a>Cleaning the Log Files</h3>
</div>
</div>
</div>
<p>
Because JE uses no-overwrite log files, the logs must be compacted or cleaned so as to conserve disk space.
</p>
<p>
JE uses the cleaner background thread to perform this task. When it runs, the cleaner thread picks
the log file with the smallest number of active records and scans each log record in it.
If the record is no longer
active in the database tree, the cleaner does nothing. If the record is still active in the tree, then
the cleaner copies the record forward to a newer log file.
</p>
<p>
Once a log file is no longer needed (that is, it no longer contains active records), then the cleaner
thread deletes the log file for you. Or, optionally, the cleaner thread can simply rename the discarded
log file with a <code class="literal">del</code> suffix.
</p>
<p>
JE uses a minimum log utilization property to determine how much cleaning to perform. The log files
contain both obsolete and utilized records. Obsolete records are records that are no longer in use, either
because they have been modified or because they have been deleted. Utilized records are those records
that are currently in use. The <code class="literal">je.cleaner.minUtilization</code> property identifies the
minimum percentage of log space that must be used by utilized records. If this minimum percentage is not
met, then log files are cleaned until the minimum percentage is met.
</p>
<p>
For information on managing the cleaner thread, see <a class="xref" href="backgroundthreads.html#cleaner" title="The Cleaner Thread">The Cleaner Thread</a>.
</p>
</div>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="btree"></a>The BTree</h3>
</div>
</div>
</div>
<p>
JE databases are internally organized as a BTree. In order to operate, JE requires the complete BTree
be available to it.
</p>
<p>
When database records are created, modified, or deleted, the modifications are represented in the BTree's
leaf nodes. Beyond leaf
node changes, database record modifications can also cause changes to other BTree nodes and structures.
</p>
</div>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="syncs"></a>Database Modifications and Syncs</h3>
</div>
</div>
</div>
<p>
When a write operation is performed in JE, the modified data
is written to a leaf node contained in the in-memory cache. If
your JE writes are performed without transactions, then the
in-memory cache is the only location guaranteed to receive a
database modification without further intervention on the part
of the application developer.
</p>
<p>
For some class of applications, this lack of a guaranteed write to disk is ideal. By not writing these modifications to
the on-disk logs, the application can avoid most of the overhead caused by disk I/O.
</p>
<p>
However, if the application requires its data to persist persist at a specific point in time, then the developer must
manually sync database modifications to the on-disk log files (again, this is only necessary for
non-transactional applications). This is done using <code class="classname">Environment.sync()</code>.
</p>
<p>
Note that syncing the cache causes JE to write all modified objects in the cache
to disk. This is probably the most expensive operation that you can perform in JE.
</p>
</div>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="normalrecovery"></a>Normal Recovery</h3>
</div>
</div>
</div>
<p>
Every time a JE environment is opened, normal recovery is run.
Because of the way that JE organizes and manages its BTrees, all it needs is leaf nodes in order to
recreate the rest of the BTree. Essentially, this is what <span class="emphasis"><em>normal recovery</em></span> is
doing recreating any missing parts of the internal BTree from leaf node information stored in the
log files.
</p>
<p>
Unlike a traditional database system, JE performs recovery for both transactional
and non-transactional operations. The integrity of the Btree is
guaranteed by JE in the face of both application and OS crashes.
</p>
</div>
</div>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="admin.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="admin.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="backup.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Part III. Administering JE Applications </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Performing Backups</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,382 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Part II. Programming with the Base API</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="prev" href="dpl_exampleinventoryread.html" title="ExampleInventoryRead.java" />
<link rel="next" href="databases.html" title="Chapter 7. Databases" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Part II. Programming with the Base API</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="dpl_exampleinventoryread.html">Prev</a> </td>
<th width="60%" align="center"> </th>
<td width="20%" align="right"> <a accesskey="n" href="databases.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="part" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h1 class="title"><a id="baseapi"></a>Part II. Programming with the Base API</h1>
</div>
</div>
</div>
<div class="partintro" lang="en" xml:lang="en">
<div></div>
<p>
This section discusses
application that are built using the JE base API. Note that
most JE applications can probably be written
using the DPL (see <a class="xref" href="dpl.html" title="Part I. Programming with the Direct Persistence Layer">Programming with the Direct Persistence Layer</a> for more
information). However, if you are porting an application
from the Berkeley DB API, then the base API is right for
you.
</p>
<div class="toc">
<p>
<b>Table of Contents</b>
</p>
<dl>
<dt>
<span class="chapter">
<a href="databases.html">7. Databases</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect1">
<a href="databases.html#DBOpen">Opening Databases</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect2">
<a href="databases.html#dwdatabase">Deferred Write Databases</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="databases.html#tempdbje">Temporary Databases</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="databases.html#dbclose">Closing Databases</a>
</span>
</dt>
</dl>
</dd>
<dt>
<span class="sect1">
<a href="dbprops.html">Database Properties</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="DBAdmin.html">Administrative Methods</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="dbUsage.html">Database Example</a>
</span>
</dt>
</dl>
</dd>
<dt>
<span class="chapter">
<a href="DBEntry.html">8. Database Records</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect1">
<a href="DBEntry.html#usingDbEntry">Using Database Records</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="usingDbt.html">Reading and Writing Database Records</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect2">
<a href="usingDbt.html#databaseWrite">Writing Records to the Database</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="usingDbt.html#databaseRead">Getting Records from the Database</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="usingDbt.html#recordDelete">Deleting Records</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="usingDbt.html#datapersist">Data Persistence</a>
</span>
</dt>
</dl>
</dd>
<dt>
<span class="sect1">
<a href="timetolive.html">Using Time to Live</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect2">
<a href="timetolive.html#ttl-specify">Specifying a TTL Value</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="timetolive.html#ttl-update">Updating a TTL Value</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="timetolive.html#ttl-remove">Deleting TTL Expiration</a>
</span>
</dt>
</dl>
</dd>
<dt>
<span class="sect1">
<a href="bindAPI.html">Using the BIND APIs</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect2">
<a href="bindAPI.html#bindPrimitive">Numerical and String Objects</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="bindAPI.html#object2dbt">Serializable Complex Objects</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="bindAPI.html#customTuple">Custom Tuple Bindings</a>
</span>
</dt>
</dl>
</dd>
<dt>
<span class="sect1">
<a href="comparator.html">Using Comparators</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect2">
<a href="comparator.html#writeCompare">Writing Comparators</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="comparator.html#setCompare">Setting Comparators</a>
</span>
</dt>
</dl>
</dd>
<dt>
<span class="sect1">
<a href="dbtUsage.html">Database Record Example</a>
</span>
</dt>
</dl>
</dd>
<dt>
<span class="chapter">
<a href="Cursors.html">9. Using Cursors</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect1">
<a href="Cursors.html#openCursor">Opening and Closing Cursors</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="Positioning.html">Getting Records Using the Cursor</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect2">
<a href="Positioning.html#diskorderedcursors">Disk Ordered Cursors</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="Positioning.html#cursorsearch">Searching for Records</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="Positioning.html#getdups">Working with Duplicate Records</a>
</span>
</dt>
</dl>
</dd>
<dt>
<span class="sect1">
<a href="PutEntryWCursor.html">Putting Records Using Cursors</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="DeleteEntryWCursor.html">Deleting Records Using Cursors</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="ReplacingEntryWCursor.html">Replacing Records Using Cursors</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="cursorUsage.html">Cursor Example</a>
</span>
</dt>
</dl>
</dd>
<dt>
<span class="chapter">
<a href="indexes.html">10. Secondary Databases</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect1">
<a href="indexes.html#DbAssociate">Opening and Closing Secondary Databases</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="keyCreator.html">Implementing Key
<span>Creators</span>
</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="secondaryProps.html">Secondary Database Properties</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="readSecondary.html">Reading Secondary Databases</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="secondaryDelete.html">Deleting Secondary Database Records</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="secondaryCursor.html">
<span>Using Secondary Cursors</span>
</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="joins.html">Database Joins</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect2">
<a href="joins.html#joinUsage">Using Join Cursors</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="joins.html#joinconfig">JoinCursor Properties</a>
</span>
</dt>
</dl>
</dd>
<dt>
<span class="sect1">
<a href="indexusage.html">Secondary Database Example</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect2">
<a href="indexusage.html#secondaryMyDbEnv">Opening Secondary Databases with
MyDbEnv</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="indexusage.html#exampleReadSecondaries">Using Secondary Databases with ExampleInventoryRead</a>
</span>
</dt>
</dl>
</dd>
</dl>
</dd>
</dl>
</div>
</div>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="dpl_exampleinventoryread.html">Prev</a> </td>
<td width="20%" align="center"> </td>
<td width="40%" align="right"> <a accesskey="n" href="databases.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">ExampleInventoryRead.java </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Chapter 7. Databases</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,792 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Using the BIND APIs</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="DBEntry.html" title="Chapter 8. Database Records" />
<link rel="prev" href="timetolive.html" title="Using Time to Live" />
<link rel="next" href="comparator.html" title="Using Comparators" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Using the BIND APIs</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="timetolive.html">Prev</a> </td>
<th width="60%" align="center">Chapter 8. Database Records</th>
<td width="20%" align="right"> <a accesskey="n" href="comparator.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="bindAPI"></a>Using the BIND APIs</h2>
</div>
</div>
</div>
<div class="toc">
<dl>
<dt>
<span class="sect2">
<a href="bindAPI.html#bindPrimitive">Numerical and String Objects</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="bindAPI.html#object2dbt">Serializable Complex Objects</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="bindAPI.html#customTuple">Custom Tuple Bindings</a>
</span>
</dt>
</dl>
</div>
<p>Except for Java String and boolean types, efficiently moving data in
and out of Java byte arrays for storage in a database can be a nontrivial
operation. To help you with this problem, JE provides the Bind APIs.
While these APIs are described in detail in the
<span>
<em class="citetitle">Berkeley DB, Java Edition Collections Tutorial</em>,
</span>
this section provides a brief introduction to using the Bind APIs with:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>Single field numerical and string objects</p>
<p>Use this if you want to store a single numerical or string object,
such as <code class="classname">Long</code>, <code class="classname">Double</code>, or
<code class="classname">String</code>.</p>
</li>
<li>
<p>Complex objects that implement Java serialization.</p>
<p>Use this if you are storing objects that implement
<code class="classname">Serializable</code> and if you do not need to sort them.
</p>
</li>
<li>
<p>Non-serialized complex objects.</p>
<p>If you are storing objects that do not implement serialization,
you can create your own custom tuple bindings. Note that you should
use custom tuple bindings even if your objects are serializable if
you want to sort on that data.</p>
</li>
</ul>
</div>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="bindPrimitive"></a>Numerical and String Objects</h3>
</div>
</div>
</div>
<p>You can use the Bind APIs to store primitive data in a <code class="classname">DatabaseEntry</code>
object. That is, you can store a single field containing one of the following types:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>
<code class="classname">String</code>
</p>
</li>
<li>
<p>
<code class="classname">Character</code>
</p>
</li>
<li>
<p>
<code class="classname">Boolean</code>
</p>
</li>
<li>
<p>
<code class="classname">Byte</code>
</p>
</li>
<li>
<p>
<code class="classname">Short</code>
</p>
</li>
<li>
<p>
<code class="classname">Integer</code>
</p>
</li>
<li>
<p>
<code class="classname">Long</code>
</p>
</li>
<li>
<p>
<code class="classname">Float</code>
</p>
</li>
<li>
<p>
<code class="classname">Double</code>
</p>
</li>
</ul>
</div>
<p>
To store primitive data using the Bind APIs:
</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>Create an <code class="classname">EntryBinding</code> object.</p>
<p>When you do this, you use <code class="classname">TupleBinding.getPrimitiveBinding()</code>
to return an appropriate binding for the conversion.</p>
</li>
<li>
<p>Use the <code class="classname">EntryBinding</code> object to place
the numerical object on the <code class="classname">DatabaseEntry</code>.</p>
</li>
</ol>
</div>
<p>Once the data is stored in the DatabaseEntry, you can put it to
the database in whatever manner you wish. For example:</p>
<a id="je_dbt6"></a>
<pre class="programlisting">package je.gettingStarted;
import com.sleepycat.bind.EntryBinding;
import com.sleepycat.bind.tuple.TupleBinding;
import com.sleepycat.je.DatabaseEntry;
...
// Need a key for the put.
try {
String aKey = "myLong";
DatabaseEntry theKey = new DatabaseEntry(aKey.getBytes("UTF-8"));
// Now build the DatabaseEntry using a TupleBinding
Long myLong = new Long(123456789l);
DatabaseEntry theData = new DatabaseEntry();
EntryBinding myBinding = TupleBinding.getPrimitiveBinding(Long.class);
myBinding.objectToEntry(myLong, theData);
// Now store it
myDatabase.put(null, theKey, theData);
} catch (Exception e) {
// Exception handling goes here
}</pre>
<p>Retrieval from the <code class="classname">DatabaseEntry</code> object is
performed in much the same way:</p>
<a id="je_dbt7"></a>
<pre class="programlisting">package je.gettingStarted;
import com.sleepycat.bind.EntryBinding;
import com.sleepycat.bind.tuple.TupleBinding;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.LockMode;
import com.sleepycat.je.OperationStatus;
...
Database myDatabase = null;
// Database open omitted for clarity
try {
// Need a key for the get
String aKey = "myLong";
DatabaseEntry theKey = new DatabaseEntry(aKey.getBytes("UTF-8"));
// Need a DatabaseEntry to hold the associated data.
DatabaseEntry theData = new DatabaseEntry();
// Bindings need only be created once for a given scope
EntryBinding myBinding = TupleBinding.getPrimitiveBinding(Long.class);
// Get it
OperationStatus retVal = myDatabase.get(null, theKey, theData,
LockMode.DEFAULT);
String retKey = null;
if (retVal == OperationStatus.SUCCESS) {
// Recreate the data.
// Use the binding to convert the byte array contained in theData
// to a Long type.
Long theLong = (Long) myBinding.entryToObject(theData);
retKey = new String(theKey.getData(), "UTF-8");
System.out.println("For key: '" + retKey + "' found Long: '" +
theLong + "'.");
} else {
System.out.println("No record found for key '" + retKey + "'.");
}
} catch (Exception e) {
// Exception handling goes here
} </pre>
</div>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="object2dbt"></a>Serializable Complex Objects</h3>
</div>
</div>
</div>
<p>Frequently your application requires you to store and manage
objects for your record data and/or keys. You may need to do this if you
are caching objects created by another process. You may also want to do
this if you want to store multiple data values on a record. When used
with just primitive data, or with objects containing a single data member,
JE database records effectively represent a single row in a two-column table.
By storing a complex object in the record, you can turn each record into
a single row in an <span class="emphasis"><em>n</em></span>-column table, where
<span class="emphasis"><em>n</em></span> is the number of data members contained by the
stored object(s).</p>
<p>In order to store objects in a
JE database, you must convert them to and from a <code class="literal">byte</code> array.
The first instinct for many Java programmers is to do this using Java
serialization. While this is functionally a correct solution, the result
is poor space-performance because this causes the class information
to be stored on every such database record. This information can be quite large
and it is redundant — the class information does not vary for serialized objects of the same type.
</p>
<p>
In other words, directly using serialization to place your objects into byte
arrays means that you will be storing a great deal of unnecessary information in
your database, which ultimately leads to larger databases and more expensive disk
I/O.
</p>
<p>The easiest way for you to solve this problem is to use the Bind
APIs to perform the serialization for you. Doing so causes the extra
object information to be saved off to a unique <code class="classname">Database</code>
dedicated for that purpose. This means that you do not have to duplicate
that information on each record in the <code class="classname">Database</code>
that your application is using to store its information.</p>
<p>
Note that when you use the Bind APIs to perform serialization, you still
receive all the benefits of serialization. You can still use arbitrarily
complex object graphs, and you still receive built-in class evolution
through the serialVersionUID (SUID) scheme. All of the Java
serialization rules apply without modification. For example, you can
implement Externalizable instead of Serializable.
</p>
<div class="sect3" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h4 class="title"><a id="bindCaveats"></a>Usage Caveats</h4>
</div>
</div>
</div>
<p>Before using the Bind APIs to perform serialization, you may
want to consider writing your own custom tuple bindings. Specifically,
avoid serialization if:
</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>
If you need to sort based on the objects your are storing.
The sort order is meaningless for the byte arrays that you
obtain through serialization. Consequently, you should not use serialization for keys if you
care about their sort order. You should
also not use serialization for record data if your
<code class="classname">Database</code> supports duplicate records and you care about sort order.
</p>
</li>
<li>
<p>
You want to minimize the size of your byte arrays. Even when using the Bind APIs to perform the
serialization the resulting <code class="literal">byte</code> array may be larger than necessary. You can achieve
more compact results by building your own custom tuple binding.
</p>
</li>
<li>
<p>
You want to optimize for speed. In general, custom tuple bindings are faster than serialization at
moving data in and out of <code class="literal">byte</code> arrays.
</p>
</li>
<li>
<p>
You are using custom comparators. In JE, comparators are instantiated and called internally whenever
databases are not accessible. Because serial bindings depend on the class catalog, a serial binding
binding cannot be used during these times. As a result, attempting to use a serial binding with a
custom comparator will result in a <code class="literal">NullPointerException</code> during environment open or
close.
</p>
</li>
</ul>
</div>
<p>
For information on building your own custom tuple binding, see <a class="xref" href="bindAPI.html#customTuple" title="Custom Tuple Bindings">Custom Tuple Bindings</a>.
</p>
</div>
<div class="sect3" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h4 class="title"><a id="objectSerial"></a>Serializing Objects</h4>
</div>
</div>
</div>
<p>To store a serializable complex object using the
Bind APIs:</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>
Implement java.io.Serializable in the class whose instances that
you want to store.
</p>
</li>
<li>
<p>Open (create) your databases. You need two. The first is the
database that you use to store your data. The second is used to
store the class information.</p>
</li>
<li>
<p>Instantiate a class catalog. You do this with
<code class="classname">com.sleepycat.bind.serial.StoredClassCatalog</code>,
and at that time you must provide a handle to an open database
that is used to store the class information.</p>
</li>
<li>
<p>Create an entry binding that uses <code class="methodname">com.sleepycat.bind.serial.SerialBinding</code>.</p>
</li>
<li>
<p>Instantiate an instance of the object that you want to
store, and place it in a <code class="classname">DatabaseEntry</code>
using the entry binding that you created in the previous step.</p>
</li>
</ol>
</div>
<p>
For example, suppose you want to store a long, double, and a
String as a record's data. Then you might create a class that
looks something like this:
</p>
<a id="je_dbt8"></a>
<pre class="programlisting">package je.gettingStarted;
import java.io.Serializable;
public class MyData implements Serializable {
private long longData;
private double doubleData;
private String description;
MyData() {
longData = 0;
doubleData = 0.0;
description = null;
}
public void setLong(long data) {
longData = data;
}
public void setDouble(double data) {
doubleData = data;
}
public void setDescription(String data) {
description = data;
}
public long getLong() {
return longData;
}
public double getDouble() {
return doubleData;
}
public String getDescription() {
return description;
}
}</pre>
<p>You can then store instances of this class as follows:</p>
<a id="je_dbt9"></a>
<pre class="programlisting">package je.gettingStarted;
import com.sleepycat.bind.EntryBinding;
import com.sleepycat.bind.serial.StoredClassCatalog;
import com.sleepycat.bind.serial.SerialBinding;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseConfig;
import com.sleepycat.je.DatabaseEntry;
...
// The key data.
String aKey = "myData";
// The data data
MyData data2Store = new MyData();
data2Store.setLong(123456789l);
data2Store.setDouble(1234.9876543);
data2Store.setDescription("A test instance of this class");
try {
// Environment open omitted for brevity
// Open the database that you will use to store your data
DatabaseConfig myDbConfig = new DatabaseConfig();
myDbConfig.setAllowCreate(true);
myDbConfig.setSortedDuplicates(true);
Database myDatabase = myDbEnv.openDatabase(null, "myDb", myDbConfig);
// Open the database that you use to store your class information.
// The db used to store class information does not require duplicates
// support.
myDbConfig.setSortedDuplicates(false);
Database myClassDb = myDbEnv.openDatabase(null, "classDb",
myDbConfig);
// Instantiate the class catalog
StoredClassCatalog classCatalog = new StoredClassCatalog(myClassDb);
// Create the binding
EntryBinding dataBinding = new SerialBinding(classCatalog,
MyData.class);
// Create the DatabaseEntry for the key
DatabaseEntry theKey = new DatabaseEntry(aKey.getBytes("UTF-8"));
// Create the DatabaseEntry for the data. Use the EntryBinding object
// that was just created to populate the DatabaseEntry
DatabaseEntry theData = new DatabaseEntry();
dataBinding.objectToEntry(data2Store, theData);
// Put it as normal
myDatabase.put(null, theKey, theData);
// Database and environment close omitted for brevity
} catch (Exception e) {
// Exception handling goes here
}</pre>
</div>
<div class="sect3" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h4 class="title"><a id="objectDeserial"></a>Deserializing Objects</h4>
</div>
</div>
</div>
<p>Once an object is stored in the database, you can retrieve the
<code class="classname">MyData</code> objects from the retrieved
<code class="classname">DatabaseEntry</code> using the Bind APIs in much the
same way as is described above. For example:</p>
<a id="je_dbt10"></a>
<pre class="programlisting">package je.gettingStarted;
import com.sleepycat.bind.EntryBinding;
import com.sleepycat.bind.serial.StoredClassCatalog;
import com.sleepycat.bind.serial.SerialBinding;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseConfig;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.LockMode;
...
// The key data.
String aKey = "myData";
try {
// Environment open omitted for brevity.
// Open the database that stores your data
DatabaseConfig myDbConfig = new DatabaseConfig();
myDbConfig.setAllowCreate(false);
Database myDatabase = myDbEnv.openDatabase(null, "myDb", myDbConfig);
// Open the database that stores your class information.
Database myClassDb = myDbEnv.openDatabase(null, "classDb",
myDbConfig);
// Instantiate the class catalog
StoredClassCatalog classCatalog = new StoredClassCatalog(myClassDb);
// Create the binding
EntryBinding dataBinding = new SerialBinding(classCatalog,
MyData.class);
// Create DatabaseEntry objects for the key and data
DatabaseEntry theKey = new DatabaseEntry(aKey.getBytes("UTF-8"));
DatabaseEntry theData = new DatabaseEntry();
// Do the get as normal
myDatabase.get(null, theKey, theData, LockMode.DEFAULT);
// Recreate the MyData object from the retrieved DatabaseEntry using
// the EntryBinding created above
MyData retrievedData = (MyData) dataBinding.entryToObject(theData);
// Database and environment close omitted for brevity
} catch (Exception e) {
// Exception handling goes here
}</pre>
</div>
</div>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="customTuple"></a>Custom Tuple Bindings</h3>
</div>
</div>
</div>
<p>
If you want to store complex objects in your database, then you can use
tuple bindings to do this. While they are more work to write and
maintain than if you were to use serialization, the
<code class="literal">byte</code> array conversion is faster. In addition, custom
tuple bindings should allow you to create <code class="literal">byte</code> arrays
that are smaller than those created by serialization. Custom tuple
bindings also allow you to optimize your BTree comparisons, whereas
serialization does not.
</p>
<p>
For information on using serialization to store complex objects, see
<a class="xref" href="bindAPI.html#object2dbt" title="Serializable Complex Objects">Serializable Complex Objects</a>.
</p>
<p>To store complex objects using a custom tuple binding:</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>Implement the class whose instances that you want to store.
Note that you do not have to implement the Serializable interface.</p>
</li>
<li>
<p>Write a tuple binding using the <code class="classname">com.sleepycat.bind.tuple.TupleBinding</code>
class.</p>
</li>
<li>
<p>Open (create) your database. Unlike serialization, you only
need one.</p>
</li>
<li>
<p>Create an entry binding that uses the tuple binding that you
implemented in step 2.</p>
</li>
<li>
<p>Instantiate an instance of the object that you want to store,
and place it in a <code class="classname">DatabaseEntry</code> using the
entry binding that you created in the previous step.</p>
</li>
</ol>
</div>
<p>
For example, suppose you want to your keys to be instances of the
following class:
</p>
<a id="je_dbt11"></a>
<pre class="programlisting">package je.gettingStarted;
public class MyData2 {
private long longData;
private Double doubleData;
private String description;
public MyData2() {
longData = 0;
doubleData = new Double(0.0);
description = "";
}
public void setLong(long data) {
longData = data;
}
public void setDouble(Double data) {
doubleData = data;
}
public void setString(String data) {
description = data;
}
public long getLong() {
return longData;
}
public Double getDouble() {
return doubleData;
}
public String getString() {
return description;
}
} </pre>
<p>In this case, you need to write a tuple binding for the
<code class="classname">MyData2</code> class. When you do this, you must
implement the <code class="methodname">TupleBinding.objectToEntry()</code>
and <code class="methodname">TupleBinding.entryToObject()</code> abstract methods.
Remember the following as you implement these methods:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>You use <code class="methodname">TupleBinding.objectToEntry()</code> to convert
objects to <code class="literal">byte</code> arrays. You use
<code class="classname">com.sleepycat.bind.tuple.TupleOutput</code> to write
primitive data types to the <code class="literal">byte</code> array. Note that
<code class="classname">TupleOutput</code> provides methods that allows
you to work with numerical types (<code class="literal">long</code>,
<code class="literal">double</code>, <code class="literal">int</code>, and so forth) and
not the corresponding <code class="literal">java.lang</code> numerical
classes.</p>
</li>
<li>
<p>The order that you write data to the <code class="literal">byte</code>
array in <code class="methodname">TupleBinding.objectToEntry()</code> is the order that
it appears in the array. So given the <code class="classname">MyData2</code>
class as an example, if you write <code class="literal">description</code>,
<code class="literal">doubleData</code>, and then <code class="literal">longData</code>,
then the resulting byte array will contain these data elements in
that order. This means that your records will sort based on the
value of the <code class="literal">description</code> data member and then
the <code class="literal">doubleData</code> member, and so forth. If you
prefer to sort based on, say, the <code class="literal">longData</code> data
member, write it to the byte array first.</p>
</li>
<li>
<p>You use <code class="methodname">TupleBinding.entryToObject()</code> to convert
the <code class="literal">byte</code> array back into an instance of your
original class. You use <code class="classname">com.sleepycat.bind.tuple.TupleInput</code>
to get data from the <code class="literal">byte</code> array.</p>
</li>
<li>
<p>The order that you read data from the <code class="literal">byte</code>
array must be exactly the same as the order in which it was written.</p>
</li>
</ul>
</div>
<p>For example:</p>
<a id="je_dbt12"></a>
<pre class="programlisting">package je.gettingStarted;
import com.sleepycat.bind.tuple.TupleBinding;
import com.sleepycat.bind.tuple.TupleInput;
import com.sleepycat.bind.tuple.TupleOutput;
public class MyTupleBinding extends TupleBinding {
// Write a MyData2 object to a TupleOutput
public void objectToEntry(Object object, TupleOutput to) {
MyData2 myData = (MyData2)object;
// Write the data to the TupleOutput (a DatabaseEntry).
// Order is important. The first data written will be
// the first bytes used by the default comparison routines.
to.writeDouble(myData.getDouble().doubleValue());
to.writeLong(myData.getLong());
to.writeString(myData.getString());
}
// Convert a TupleInput to a MyData2 object
public Object entryToObject(TupleInput ti) {
// Data must be read in the same order that it was
// originally written.
Double theDouble = new Double(ti.readDouble());
long theLong = ti.readLong();
String theString = ti.readString();
MyData2 myData = new MyData2();
myData.setDouble(theDouble);
myData.setLong(theLong);
myData.setString(theString);
return myData;
}
} </pre>
<p>In order to use the tuple binding, instantiate the binding and
then use:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p><code class="methodname">MyTupleBinding.objectToEntry()</code> to
convert a MyData2 object to a <code class="classname">DatabaseEntry</code>.</p>
</li>
<li>
<p><code class="methodname">MyTupleBinding.entryToObject()</code> to convert
a <code class="classname">DatabaseEntry</code> to a <code class="classname">MyData2</code>
object.</p>
</li>
</ul>
</div>
<p>For example:</p>
<a id="je_dbt13"></a>
<pre class="programlisting">package je.gettingStarted;
import com.sleepycat.bind.tuple.TupleBinding;
import com.sleepycat.je.DatabaseEntry;
...
TupleBinding keyBinding = new MyTupleBinding();
MyData2 theKeyData = new MyData2();
theKeyData.setLong(123456789l);
theKeyData.setDouble(new Double(12345.6789));
theKeyData.setString("My key data");
DatabaseEntry myKey = new DatabaseEntry();
try {
// Store theKeyData in the DatabaseEntry
keyBinding.objectToEntry(theKeyData, myKey);
...
// Database put and get activity omitted for clarity
...
// Retrieve the key data
theKeyData = (MyData2) keyBinding.entryToObject(myKey);
} catch (Exception e) {
// Exception handling goes here
}</pre>
</div>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="timetolive.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="DBEntry.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="comparator.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Using Time to Live </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Using Comparators</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,131 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Sizing the Cache</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="administration.html" title="Chapter 12. Administering Berkeley DB Java Edition Applications" />
<link rel="prev" href="backgroundthreads.html" title="Managing the Background Threads" />
<link rel="next" href="diskthreshold.html" title="Setting Disk Thresholds" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Sizing the Cache</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="backgroundthreads.html">Prev</a> </td>
<th width="60%" align="center">Chapter 12. Administering Berkeley DB Java Edition Applications</th>
<td width="20%" align="right"> <a accesskey="n" href="diskthreshold.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="cachesize"></a>Sizing the Cache</h2>
</div>
</div>
</div>
<p>
By default, your cache is limited to a percentage of the JVM maximum
memory as specified by the <code class="literal">-Xmx</code> parameter. You can
change this percentage by using the <code class="literal">je.maxMemoryPercent</code> property
or through <code class="methodname">EnvironmentMutableConfig.setCachePercent()</code>.
That is, the maximum amount of memory available to your cache is
normally calculated as:
</p>
<pre class="programlisting">je.maxMemoryPercent * JVM_maximum_memory</pre>
<p>
You can find out what the value for this property is by using
<code class="methodname">EnvironmentConfig.getCachePercent()</code>.
</p>
<p>
Note that you can cause JE to use a fixed maximum cache size by
using <code class="literal">je.maxMemory</code> or by using
<code class="methodname">EnvironmentConfig.setCacheSize()</code>.
</p>
<p>
Also, not every JVM is capable of identifying the amount of memory requested via
the <code class="literal">-Xmx</code> parameter. For those JVMs you must use
<code class="literal">je.maxMemory</code> to change your maximum cache size. The
default maximum memory available to your cache in this case is 38M.
</p>
<p>
Of the amount of memory allowed for your cache, 93% is used for the internal BTree and the other 7% is
used for internal buffers. When your application first starts up, the 7% for buffers is immediately allocated.
The remainder of the cache grows lazily as your application reads and writes data.
</p>
<p>
In order for your application to start up successfully, the Java virtual machine must have enough memory
available to it (as identified by the <code class="literal">-Xmx</code> command line switch) for both your application and
7% of your maximum cache value. In order for your application to run continuously (all the while loading data
into the cache), you must make sure your JVM has enough memory for your application plus the maximum cache size.
</p>
<p>
The best way to determine how large your cache needs to be is to put your application into a production
environment and watch to see how much disk I/O is occurring. If the application is going to disk quite a lot to
retrieve database records, then you should increase the size of your cache (provided that you have enough memory
to do so).
</p>
<p>
You can also use the
<code class="methodname">com.sleepycat.je.util.DbCacheSize</code> utility
to obtain a rough estimate of how large your cache needs to be for
a given number of records and record characteristics. The utility
returns an estimate of the cache size to hold
the specified number of records in memory. See the
<a class="ulink" href="../java/com/sleepycat/je/util/DbCacheSize.html" target="_top">DbCacheSize javadoc</a>
for information on the utility's usage.
</p>
<p>
In order to determine how frequently your application is going to disk for database records not found in the
cache, you can examine the value returned by <code class="methodname">EnvironmentStats.getNCacheMiss()</code>.
</p>
<p>
<code class="methodname">EnvironmentStats.getNCacheMiss()</code> identifies the total number of requests for
database objects that were
not serviceable from the cache. This value is cumulative since the application started. The faster this number grows,
the more your application is going to disk to service database operations. Upon application startup you can
expect this value to grow quite rapidly. However, as time passes and your cache is seeded with your most
frequently accessed database records, what you want is for this number's growth to be zero or at least very
small.
</p>
<p>
Note that this statistic can only be collected from within the application itself or using the JMX extension
(see <a class="xref" href="jmx.html" title="JConsole and JMX Support">JConsole and JMX Support</a>).
</p>
<p>
For more information on collecting this statistic, see <a class="xref" href="envStats.html" title="Environment Statistics">Environment Statistics</a>.
</p>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="backgroundthreads.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="administration.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="diskthreshold.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Managing the Background Threads </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Setting Disk Thresholds</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,117 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Performing Catastrophic Recovery</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="backuprestore.html" title="Chapter 11. Backing up and Restoring Berkeley DB Java Edition Applications" />
<link rel="prev" href="backup.html" title="Performing Backups" />
<link rel="next" href="hotfailover.html" title="Hot Standby" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Performing Catastrophic Recovery</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="backup.html">Prev</a> </td>
<th width="60%" align="center">Chapter 11. Backing up and Restoring Berkeley DB Java Edition Applications</th>
<td width="20%" align="right"> <a accesskey="n" href="hotfailover.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="catastrophicrecovery"></a>Performing Catastrophic Recovery</h2>
</div>
</div>
</div>
<p>
Catastrophic recovery is necessary whenever your environment and/or database have been lost or corrupted
due to a media failure (disk failure, for example). Catastrophic recovery is also required if normal
recovery fails for any reason.
</p>
<p>
In order to perform catastrophic recovery, you must have a full back up of your databases. You will use
this backup to restore your database. See <a class="xref" href="backup.html" title="Performing Backups">Performing Backups</a> for
information on running back ups.
</p>
<p>
To perform catastrophic recovery:
</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>
Shut down your application.
</p>
</li>
<li>
<p>
Delete the contents of your environment home directory (the one that experienced a catastrophic
failure), if there is anything there.
</p>
</li>
<li>
<p>
Copy your most recent full backup into your environment home directory.
If you are using subdirectories to store your log files, be sure to place
the recovered log files back into the subdirectory from which they were
originally backed up.
</p>
</li>
<li>
<p>
If you are using a backup utility that runs incremental backups of your
environment directory, copy any log files generated since the time of your
last full backup. Be sure to restore all log files in the order that they
were written. The order is important because it is possible the same log
file appears in multiple archives, and you want to run recovery using the
most recent version of each log file. Also, if you are using subdirectories to
store your log files, be sure to maintain the relationship between your log files
and the subdirectory in which JE originally placed them.
</p>
</li>
<li>
<p>
Open the environment as normal. JE's normal recovery will run, which will bring your database
to a consistent state relative to the changed data found in your log files.
</p>
</li>
</ol>
</div>
<p>
You are now done restoring your database.
</p>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="backup.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="backuprestore.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="hotfailover.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Performing Backups </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Hot Standby</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,563 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>The Command Line Tools</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="administration.html" title="Chapter 12. Administering Berkeley DB Java Edition Applications" />
<link rel="prev" href="diskthreshold.html" title="Setting Disk Thresholds" />
<link rel="next" href="managelogging.html" title="Logging" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">The Command Line Tools</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="diskthreshold.html">Prev</a> </td>
<th width="60%" align="center">Chapter 12. Administering Berkeley DB Java Edition Applications</th>
<td width="20%" align="right"> <a accesskey="n" href="managelogging.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="commandlinetools"></a>The Command Line Tools</h2>
</div>
</div>
</div>
<div class="toc">
<dl>
<dt>
<span class="sect2">
<a href="commandlinetools.html#DbDump">DbDump</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="commandlinetools.html#DbLoad">DbLoad</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="commandlinetools.html#DbVerify">DbVerify</a>
</span>
</dt>
</dl>
</div>
<p>
JE ships with several command line tools that
you can use to help you manage your databases. They are:
</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>
<a class="ulink" href="../java/com/sleepycat/je/util/DbDump.html" target="_top">DbDump</a>
</p>
<p>
Dumps a database to a user-readable format.
</p>
</li>
<li>
<p>
<a class="ulink" href="../java/com/sleepycat/je/util/DbLoad.html" target="_top">DbLoad</a>
</p>
<p>
Loads a database from the output produced by <code class="literal">DbDump</code>
</p>
</li>
<li>
<p>
<a class="ulink" href="../java/com/sleepycat/je/util/DbVerify.html" target="_top">DbVerify</a>
</p>
<p>
Verifies the structure of a database.
</p>
</li>
</ul>
</div>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="DbDump"></a>DbDump</h3>
</div>
</div>
</div>
<p>
Dumps a database to a flat-text representation. Options are:
</p>
<div class="variablelist">
<dl>
<dt>
<span class="term">
<span class="bold">
<strong><code class="option">-f</code> </strong>
</span>
</span>
</dt>
<dd>
<p>
Identifies the file to which the output from this command is written.
The console (standard out) is used by default.
</p>
</dd>
<dt>
<span class="term">
<span class="bold">
<strong><code class="option">-h</code> </strong>
</span>
</span>
</dt>
<dd>
<p>
Identifies the environment's directory. This parameter is required.
</p>
</dd>
<dt>
<span class="term">
<span class="bold">
<strong><code class="option">-l</code> </strong>
</span>
</span>
</dt>
<dd>
<p>
Lists the databases contained in the environment. If the <code class="option">-s</code> is
not provided, then this argument is required.
</p>
</dd>
<dt>
<span class="term">
<span class="bold">
<strong><code class="option">-p</code> </strong>
</span>
</span>
</dt>
<dd>
<p>
Prints database records in human-readable format.
</p>
</dd>
<dt>
<span class="term">
<span class="bold">
<strong><code class="option">-r</code> </strong>
</span>
</span>
</dt>
<dd>
<p>
Salvage data from a possibly corrupt file. When used on a uncorrupted database, this option
should return data equivalent to a normal dump, but most likely in a different order.
</p>
<p>
This option causes the ensuing output to go to a file named
<span class="emphasis"><em>dbname</em></span><code class="literal">.dump</code> where
<span class="emphasis"><em>dbname</em></span> is the name of the database you are dumping. The
file is placed in the current working directory.
</p>
</dd>
<dt>
<span class="term">
<span class="bold">
<strong><code class="option">-R</code> </strong>
</span>
</span>
</dt>
<dd>
<p>
Aggressively salvage data from a possibly corrupt file. This option differs from the -r option
in that it will return all possible data from the file at the risk of also returning already
deleted or otherwise nonsensical items. Data dumped in this fashion will almost certainly have
to be edited by hand or other means before the data is ready for reload into another database.
</p>
<p>
This option causes the ensuing output to go to a file named
<span class="emphasis"><em>dbname</em></span><code class="literal">.dump</code> where
<span class="emphasis"><em>dbname</em></span> is the name of the database you are dumping. The
file is placed in the current working directory.
</p>
</dd>
<dt>
<span class="term">
<span class="bold">
<strong><code class="option">-s</code> </strong>
</span>
</span>
</dt>
<dd>
<p>
Identifies the database to be dumped. If this option is not specified, then the <code class="option">-l</code> is required.
</p>
</dd>
<dt>
<span class="term">
<span class="bold">
<strong><code class="option">-v</code> </strong>
</span>
</span>
</dt>
<dd>
<p>
Prints progress information to the console for
<code class="literal">-r</code> or <code class="literal">-R</code> mode.
</p>
</dd>
<dt>
<span class="term">
<span class="bold">
<strong><code class="option">-V</code> </strong>
</span>
</span>
</dt>
<dd>
<p>
Prints the database version number and then quits. All other command line options are ignored.
</p>
</dd>
</dl>
</div>
<p>
For example:
</p>
<pre class="programlisting">&gt; <strong class="userinput"><code>java com.sleepycat.je.util.DbDump -h . -p -s VendorDB</code></strong>
VERSION=3
format=print
type=btree
database=VendorDB
dupsort=false
HEADER=END
Mom's Kitchen
sr\01\01xpt\00\0d53 Yerman Ct.t\00\0c763 554 9200t\00\0bMiddle Townt\00
\0eMaggie Kultgent\00\10763 554 9200 x12t\00\02MNt\00\0dMom's Kitchent\00
\0555432
Off the Vine
sr\01\01xpt\00\10133 American Ct.t\00\0c563 121 3800t\00\0aCentennialt\00
\08Bob Kingt\00\10563 121 3800 x54t\00\02IAt\00\0cOff the Vinet\00\0552002
Simply Fresh
sr\01\01xpt\00\1115612 Bogart Lanet\00\0c420 333 3912t\00\08Harrigant\00
\0fCheryl Swedbergt\00\0c420 333 3952t\00\02WIt\00\0cSimply Fresht\00\0
553704
The Baking Pan
sr\01\01xpt\00\0e1415 53rd Ave.t\00\0c320 442 2277t\00\07Dutchint\00\09
Mike Roant\00\0c320 442 6879t\00\02MNt\00\0eThe Baking Pant\00\0556304
The Pantry
sr\01\01xpt\00\111206 N. Creek Wayt\00\0c763 555 3391t\00\0bMiddle Town
t\00\0fSully Beckstromt\00\0c763 555 3391t\00\02MNt\00\0aThe Pantryt\00
\0555432
TriCounty Produce
sr\01\01xpt\00\12309 S. Main Streett\00\0c763 555 5761t\00\0bMiddle Townt
\00\0dMort Dufresnet\00\0c763 555 5765t\00\02MNt\00\11TriCounty Producet
\00\0555432
DATA=END
&gt; </pre>
</div>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="DbLoad"></a>DbLoad</h3>
</div>
</div>
</div>
<p>
Loads a database from the output produced by <code class="literal">DbDump</code>.
Options are:
</p>
<div class="variablelist">
<dl>
<dt>
<span class="term">
<span class="bold">
<strong><code class="option">-c</code> </strong>
</span>
</span>
</dt>
<dd>
<p>Specifies configuration options. The options supplied here override the corresponding options
that appear in the data that is being loaded. This option takes values of the form
<span class="emphasis"><em>name</em></span>=<span class="emphasis"><em>value</em></span>, where <span class="emphasis"><em>name</em></span>
is the configuration option that you are overriding and <span class="emphasis"><em>value</em></span>
is the new value for the option.
</p>
<p>
The following options can be specified:
</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>
<code class="literal">database</code>
</p>
<p>
The name of the database to be loaded. This option duplicates the functionality of
this command's <code class="option">-s</code> command line option.
</p>
</li>
<li>
<p>
<code class="literal">dupsort</code>
</p>
<p>
Indicates whether duplicates are allowed in the database. A value of
<code class="literal">true</code> allows duplicates in the database.
</p>
</li>
</ul>
</div>
</dd>
<dt>
<span class="term">
<span class="bold">
<strong><code class="option">-f</code> </strong>
</span>
</span>
</dt>
<dd>
<p>
Identifies the file from which the database is to be loaded.
</p>
</dd>
<dt>
<span class="term">
<span class="bold">
<strong><code class="option">-n</code> </strong>
</span>
</span>
</dt>
<dd>
<p>
Do not overwrite existing keys in the database when loading into an already existing database.
If a key/data pair cannot be loaded into the database for this reason, a warning message is
displayed on the standard error output, and the key/data pair are skipped
</p>
</dd>
<dt>
<span class="term">
<span class="bold">
<strong><code class="option">-h</code> </strong>
</span>
</span>
</dt>
<dd>
<p>
Identifies the environment's directory. This parameter is required.
</p>
</dd>
<dt>
<span class="term">
<span class="bold">
<strong><code class="option">-l</code> </strong>
</span>
</span>
</dt>
<dd>
<p>
Allows loading databases that were dumped with the Berkeley DB C
product, when the dump file contains parameters not known to JE.
</p>
</dd>
<dt>
<span class="term">
<span class="bold">
<strong><code class="option">-s</code> </strong>
</span>
</span>
</dt>
<dd>
<p>
Overrides the database name, causing the data to be loaded into a database that uses the name
supplied to this parameter.
</p>
</dd>
<dt>
<span class="term">
<span class="bold">
<strong><code class="option">-T</code> </strong>
</span>
</span>
</dt>
<dd>
<p>
Causes a flat text file to be loaded into the database.
</p>
<p>
The input must be paired lines of text, where the first line of the pair is the key item,
and the second line of the pair is its corresponding data item.
</p>
<p>
A simple escape mechanism, where newline and backslash (\) characters are special, is
applied to the text input. Newline characters are interpreted as record separators.
Backslash characters in the text will be interpreted in one of two ways: If the backslash
character precedes another backslash character, the pair will be interpreted as a literal
backslash. If the backslash character precedes any other character, the two characters
following the backslash will be interpreted as a hexadecimal specification of a single
character; for example, \0a is a newline character in the ASCII character set.
</p>
<p>
For this reason, any backslash or newline characters that naturally occur in the text input
must be escaped to avoid misinterpretation by db_load.
</p>
</dd>
<dt>
<span class="term">
<span class="bold">
<strong><code class="option">-v</code> </strong>
</span>
</span>
</dt>
<dd>
<p>
Report periodic load status to the console.
</p>
</dd>
<dt>
<span class="term">
<span class="bold">
<strong><code class="option">-V</code> </strong>
</span>
</span>
</dt>
<dd>
<p>
Prints the database version number and then quits. All other command line options are ignored.
</p>
</dd>
</dl>
</div>
<p>
For example:
</p>
<pre class="programlisting">&gt; <strong class="userinput"><code>java com.sleepycat.je.util.DbDump -h . -s VendorDB -f vendordb.txt</code></strong>
&gt; <strong class="userinput"><code>java com.sleepycat.je.util.DbLoad -h . -f vendordb.txt</code></strong>
&gt; </pre>
</div>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="DbVerify"></a>DbVerify</h3>
</div>
</div>
</div>
<p>
Examines the identified database for errors. Options are:
</p>
<div class="variablelist">
<dl>
<dt>
<span class="term">
<span class="bold">
<strong><code class="option">-h</code> </strong>
</span>
</span>
</dt>
<dd>
<p>
Identifies the environment's directory. This parameter is required.
</p>
</dd>
<dt>
<span class="term">
<span class="bold">
<strong><code class="option">-q</code> </strong>
</span>
</span>
</dt>
<dd>
<p>
Suppress the printing of any error descriptions. Instead, simply exit success or failure.
</p>
</dd>
<dt>
<span class="term">
<span class="bold">
<strong><code class="option">-s</code> </strong>
</span>
</span>
</dt>
<dd>
<p>
Identifies the database to be verified. This parameter is required.
</p>
</dd>
<dt>
<span class="term">
<span class="bold">
<strong><code class="option">-V</code> </strong>
</span>
</span>
</dt>
<dd>
<p>
Prints the database version number and then quits. All other command line options are ignored.
</p>
</dd>
<dt>
<span class="term">
<span class="bold">
<strong><code class="option">-v</code> </strong>
</span>
</span>
</dt>
<dd>
<p>
Report intermediate statistics every <span class="emphasis"><em>N</em></span> leaf nodes, where
<span class="emphasis"><em>N</em></span> is the value that you provide this parameter.
</p>
</dd>
</dl>
</div>
<p>
For example:
</p>
<pre class="programlisting">&gt; <strong class="userinput"><code>java com.sleepycat.je.util.DbVerify -h . -s VendorDB</code></strong>
&lt;BtreeStats&gt;
&lt;BottomInternalNodesByLevel total="1"&gt;
&lt;Item level="1" count="1"/&gt;
&lt;/BottomInternalNodesByLevel&gt;
&lt;InternalNodesByLevel total="1"&gt;
&lt;Item level="2" count="1"/&gt;
&lt;/InternalNodesByLevel&gt;
&lt;LeafNodes count="6"/&gt;
&lt;DeletedLeafNodes count="0"/&gt;
&lt;DuplicateCountLeafNodes count="0"/&gt;
&lt;MainTreeMaxDepth depth="2"/&gt;
&lt;DuplicateTreeMaxDepth depth="0"/&gt;
&lt;/BtreeStats&gt;</pre>
</div>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="diskthreshold.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="administration.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="managelogging.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Setting Disk Thresholds </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Logging</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,260 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Using Comparators</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="DBEntry.html" title="Chapter 8. Database Records" />
<link rel="prev" href="bindAPI.html" title="Using the BIND APIs" />
<link rel="next" href="dbtUsage.html" title="Database Record Example" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Using Comparators</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="bindAPI.html">Prev</a> </td>
<th width="60%" align="center">Chapter 8. Database Records</th>
<td width="20%" align="right"> <a accesskey="n" href="dbtUsage.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="comparator"></a>Using Comparators</h2>
</div>
</div>
</div>
<div class="toc">
<dl>
<dt>
<span class="sect2">
<a href="comparator.html#writeCompare">Writing Comparators</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="comparator.html#setCompare">Setting Comparators</a>
</span>
</dt>
</dl>
</div>
<p>Internally, JE databases are organized as BTrees.
This means that most database operations
(inserts, deletes, reads, and so forth) involve BTree node
comparisons. This comparison most frequently occurs based on database
keys, but if your database supports duplicate records then
comparisons can also occur based on the database data.
</p>
<p>
By default, JE performs all such comparisons using a byte-by-byte
lexicographic comparison. This mechanism works well for most data.
However, in some cases you may need to specify your own comparison
routine. One frequent reason for this is to perform a language sensitive
lexical ordering of string keys.
</p>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="writeCompare"></a>Writing Comparators</h3>
</div>
</div>
</div>
<p>
You override the default comparison function by providing a Java
<code class="classname">Comparator</code> class to the database.
The Java <code class="classname">Comparator</code> interface requires you to implement the
<code class="methodname">Comparator.compare()</code> method
(see <a class="ulink" href="http://java.sun.com/j2se/1.4.2/docs/api/java/util/Comparator.html" target="_top">http://java.sun.com/j2se/1.4.2/docs/api/java/util/Comparator.html</a> for details).
</p>
<p>
JE passes your <code class="methodname">Comparator.compare()</code> method
the <code class="literal">byte</code> arrays that you stored in the database. If
you know how your data is organized in the <code class="literal">byte</code>
array, then you can write a comparison routine that directly examines
the contents of the arrays. Otherwise, you have to reconstruct your
original objects, and then perform the comparison.
</p>
<p>
For example, suppose you want to perform unicode lexical comparisons
instead of UTF-8 byte-by-byte comparisons. Then you could provide a
comparator that uses <code class="methodname">String.compareTo()</code>,
which performs a Unicode comparison of two strings (note that for
single-byte roman characters, Unicode comparison and UTF-8
byte-by-byte comparisons are identical this is something you
would only want to do if you were using multibyte unicode characters
with JE). In this case, your comparator would look like the
following:
</p>
<a id="je_dbt14"></a>
<pre class="programlisting">package je.gettingStarted;
import java.util.Comparator;
public class MyDataComparator implements Comparator {
public MyDataComparator() {}
public int compare(Object d1, Object d2) {
byte[] b1 = (byte[])d1;
byte[] b2 = (byte[])d2;
String s1 = new String(b1, "UTF-8");
String s2 = new String(b2, "UTF-8");
return s1.compareTo(s2);
}
} </pre>
</div>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="setCompare"></a>Setting Comparators</h3>
</div>
</div>
</div>
<p>
You specify a <code class="classname">Comparator</code> using the following
methods. Note that by default these methods can only be used at database
creation time, and they are ignored for normal database opens. Also,
note that JE uses the no-argument constructor for these comparators.
Further, it is not allowable for there to be a mutable state in these
comparators or else unpredictable results will occur.
</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>
<code class="methodname">DatabaseConfig.setBtreeComparator()</code>
</p>
<p>
Sets the Java <code class="classname">Comparator</code> class used
to compare two keys in the database.
</p>
</li>
<li>
<p>
<code class="methodname">DatabaseConfig.setDuplicateComparator()</code>
</p>
<p>
Sets the Java <code class="classname">Comparator</code> class used to compare the
data on two duplicate records in the database. This comparator is
used only if the database supports duplicate records.
</p>
</li>
</ul>
</div>
<p>
You can use the above methods to set a database's comparator after
database creation time if you explicitly indicate that the comparator
is to be overridden. You do this by using the following methods:
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;">
<h3 class="title">Note</h3>
<p>
If you override your comparator, the new comparator must preserve the
sort order implemented by your original comparator. That is, the new
comparator and the old comparator must return the same value for the
comparison of any two valid objects. Failure to observe this constraint
will cause unpredictable results for your application.
</p>
<p>
If you want to change the fundamental sort order for your database, back
up the contents of the database, delete the database, recreate it, and
then reload its data.
</p>
</div>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>
<code class="methodname">DatabaseConfig.setOverrideBtreeComparator()</code>
</p>
<p>
If set to <code class="literal">true</code>, causes the database's Btree
comparator to be overridden with the
<code class="classname">Comparator</code> specified on
<code class="methodname">DatabaseConfig.setBtreeComparator()</code>. This
method can be used to change the comparator post-environment
creation.
</p>
</li>
<li>
<p>
<code class="methodname">DatabaseConfig.setOverrideDuplicateComparator()</code>
</p>
<p>
If set to <code class="literal">true</code>, causes the database's
duplicates comparator to be overridden with the
<code class="classname">Comparator</code> specified on
<code class="methodname">DatabaseConfig.setDuplicateComparator()</code>.
</p>
</li>
</ul>
</div>
<p>For example, to use the <code class="classname">Comparator</code>
described in the previous section:</p>
<a id="je_dbt15"></a>
<pre class="programlisting">package je.gettingStarted;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseConfig;
import com.sleepycat.je.DatabaseException;
import java.util.Comparator;
...
// Environment open omitted for brevity
try {
// Get the database configuration object
DatabaseConfig myDbConfig = new DatabaseConfig();
myDbConfig.setAllowCreate(true);
// Set the duplicate comparator class
myDbConfig.setDuplicateComparator(MyDataComparator.class);
// Open the database that you will use to store your data
myDbConfig.setSortedDuplicates(true);
Database myDatabase = myDbEnv.openDatabase(null, "myDb", myDbConfig);
} catch (DatabaseException dbe) {
// Exception handling goes here
}</pre>
</div>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="bindAPI.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="DBEntry.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="dbtUsage.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Using the BIND APIs </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Database Record Example</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,171 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Appendix A. Concurrent Processing in Berkeley DB Java Edition</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="prev" href="managelogging.html" title="Logging" />
<link rel="next" href="multiprocess.html" title="Multiprocess Applications" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Appendix A. Concurrent Processing in Berkeley DB Java Edition</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="managelogging.html">Prev</a> </td>
<th width="60%" align="center"> </th>
<td width="20%" align="right"> <a accesskey="n" href="multiprocess.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="appendix" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title"><a id="concurrentProcessing"></a>Appendix A. Concurrent Processing in Berkeley DB Java Edition</h2>
</div>
</div>
</div>
<p>
An in-depth description of concurrent processing in JE is beyond the scope of this manual. However, there are
a few things that you should be aware of as you explore JE. Note that many of these topics are described in
greater detail in other parts of this book. This section is intended only to summarize JE concurrent
processing.
</p>
<p>
Also, this appendix touches on a topic not
discussed in any detail in this manual: transactions. Transactional usage is
optional but nevertheless very commonly used for JE
applications, especially when writing multi-threaded or
multi-process applications. However, transactions also
represent a topic that is too large for this book. To read a
thorough description of JE and transactional processing,
see the <em class="citetitle">Berkeley DB, Java Edition Getting Started with Transaction Processing</em> guide.
</p>
<p>
This appendix first describes concurrency with multithreaded applications. It then goes on to describe
<a class="xref" href="multiprocess.html" title="Multiprocess Applications">Multiprocess Applications</a>.
</p>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="multithreaded"></a>Multithreaded Applications</h2>
</div>
</div>
</div>
<p>
Note the following if you are writing an application that will use multiple threads for reading and writing
JE databases:
</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>
JE database and environment handles are free-threaded (that is, are thread safe), so from a mechanical perspective you
do not have to synchronize access to them when they are used by multiple threads of control.
</p>
</li>
<li>
<p>
It is dangerous to close environments and databases when other database operations are in
progress. So if you are going to share handles for these objects across threads, you should
architect your application such that there is no possibility of a thread closing a handle when
another thread is using that handle.
</p>
</li>
<li>
<p>
If a transaction is shared across threads, it is safe to call <code class="methodname">transaction.abort()</code> from
any thread. However, be aware that any thread that attempts a database operation using an aborted
transaction will throw a <code class="classname">DatabaseException</code>. You should architect your
application such that your threads are able to gracefully deal with some other thread aborting the
current transaction.
</p>
</li>
<li>
<p>
If a transaction is shared across threads, make sure that
<code class="methodname">transaction.commit()</code> can never be called until all threads participating in
the transaction have completed their database operations.
</p>
</li>
<li>
<p>
Locking is performed at the database record level.
JE always checks for lock conflicts, which can be caused either by operations that run for
too long a period of time, or by deadlocks. JE decides that a lock conflict has occured when
the lock cannot be obtained within a set timeout
period. If it cannot, regardless of why the lock could
not be obtained, then <code class="classname">LockConflictException</code> is thrown.
</p>
</li>
<li>
<p>
A non-transactional operation that reads a record locks it for the duration of the read.
While locked for read, a write lock can not be obtained on that record. However, another read lock
can be obtained for that record. This means that for threaded applications, multiple threads can
simultaneously read a record, but no thread can write to the record while a read is in progress.
</p>
<p>
Note that if you are performing uncommitted reads, then no locking is performed for that read. Instead,
JE uses internal mechanisms to ensure that the data you are reading is consistent (that is, it
will not change mid-read).
</p>
<p>
Finally, it is possible to specify that you want a write lock for your read operation. You do this
using <code class="literal">LockMode.RMW</code>. Use <code class="literal">RMW</code> when you know that your read will
subsequently be followed up with a write operation. Doing so can help to avoid lock conflicts.
</p>
</li>
<li>
<p>
An operation that writes to a record obtains a write lock on that record. While the write lock is in
progress, no other locks can be obtained for that record (either read or write).
</p>
</li>
<li>
<p>
All locks, read or write, obtained from within a transaction are held until the transaction is either
committed or aborted.
This means that the longer a transaction lives, the more likely other threads in your application
are to run into lock conflicts. That is, write operations
performed outside of the scope of the transaction will not be able to obtain a lock on those records
while the transaction is in progress. Also, by default, reads performed outside the scope of the
transaction will not be able to lock records written by the transaction. However, this behavior can be
overridden by configuring your reader to perform uncommitted reads.
</p>
</li>
</ul>
</div>
</div>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="managelogging.html">Prev</a> </td>
<td width="20%" align="center"> </td>
<td width="40%" align="right"> <a accesskey="n" href="multiprocess.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Logging </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Multiprocess Applications</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,284 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Cursor Example</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="Cursors.html" title="Chapter 9. Using Cursors" />
<link rel="prev" href="ReplacingEntryWCursor.html" title="Replacing Records Using Cursors" />
<link rel="next" href="indexes.html" title="Chapter 10. Secondary Databases" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Cursor Example</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="ReplacingEntryWCursor.html">Prev</a> </td>
<th width="60%" align="center">Chapter 9. Using Cursors</th>
<td width="20%" align="right"> <a accesskey="n" href="indexes.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="cursorUsage"></a>Cursor Example</h2>
</div>
</div>
</div>
<p>In <a class="xref" href="dbUsage.html" title="Database Example">Database Example</a> we wrote an
application that loaded two <code class="classname">Database</code> objects with vendor
and inventory information. In this example, we will use those databases to
display all of the items in the inventory database. As a part of showing
any given inventory item, we will look up the vendor who can provide the
item and show the vendor's contact information.</p>
<p>To do this, we create the <code class="classname">ExampleInventoryRead</code>
application. This application reads and displays all inventory records by:</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>Opening the environment and then the inventory, vendor, and
class catalog <code class="classname">Database</code> objects. We do this using the
<code class="classname">MyDbEnv</code> class. See <a class="xref" href="dbtUsage.html#dbenvStoredClass" title="Example 8.4 Stored Class Catalog Management with MyDbEnv">Stored Class Catalog Management with MyDbEnv</a>
for a description of this class.</p>
</li>
<li>
<p>Obtaining a cursor from the inventory <code class="classname">Database</code>.</p>
</li>
<li>
<p>Steps through the <code class="classname">Database</code>, displaying
each record as it goes.</p>
</li>
<li>
<p>To display the Inventory record, the custom tuple binding that
we created in <a class="xref" href="dbtUsage.html#InventoryBinding" title="Example 8.3 InventoryBinding.java">InventoryBinding.java</a> is used.</p>
</li>
<li>
<p><code class="methodname">Database.get()</code> is used to obtain the vendor that corresponds to
the inventory item.</p>
</li>
<li>
<p>A serial binding is used to convert the
<code class="classname">DatabaseEntry</code> returned
by the <code class="methodname">get()</code> to a Vendor object.</p>
</li>
<li>
<p>The contents of the Vendor object are displayed.</p>
</li>
</ol>
</div>
<p>We implemented the <code class="classname">Vendor</code> class in <a class="xref" href="dbtUsage.html#vendor" title="Example 8.2 Vendor.java">Vendor.java</a>. We implemented the
<code class="classname">Inventory</code> class in <a class="xref" href="dbtUsage.html#inventory" title="Example 8.1 Inventory.java">Inventory.java</a>.</p>
<p>The full implementation of <code class="classname">ExampleInventoryRead</code>
can be found in:
</p>
<pre class="programlisting"><span class="emphasis"><em>JE_HOME</em></span>/examples/je/gettingStarted/ExampleInventoryRead.java</pre>
<p>
where <code class="literal"><span class="emphasis"><em>JE_HOME</em></span></code> is the location where you
placed your JE
distribution.
</p>
<div class="example">
<a id="EIR"></a>
<p class="title">
<b>Example 9.1 ExampleInventoryRead.java</b>
</p>
<div class="example-contents">
<p>To begin, we import the necessary classes:</p>
<a id="je_cursor10"></a>
<pre class="programlisting">// file ExampleInventoryRead.java
package je.gettingStarted;
import com.sleepycat.bind.EntryBinding;
import com.sleepycat.bind.serial.SerialBinding;
import com.sleepycat.bind.tuple.TupleBinding;
import com.sleepycat.je.Cursor;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.LockMode;
import com.sleepycat.je.OperationStatus;
import java.io.File;
import java.io.IOException; </pre>
<p>Next we declare our class and set up some global variables. Note a
<code class="classname">MyDbEnv</code> object is instantiated here. We can do
this because its constructor never throws an exception. See <a class="xref" href="dbUsage.html" title="Database Example">Database Example</a> for its implementation
details.</p>
<a id="je_cursor11"></a>
<pre class="programlisting">public class ExampleInventoryRead {
private static File myDbEnvPath =
new File("/tmp/JEDB");
// Encapsulates the database environment and databases.
private static MyDbEnv myDbEnv = new MyDbEnv();
private static TupleBinding inventoryBinding;
private static EntryBinding vendorBinding;</pre>
<p>
Next we create the <code class="methodname">ExampleInventoryRead.usage()</code> and
<code class="methodname">ExampleInventoryRead.main()</code> methods.
We perform almost all of our exception handling from <code class="methodname">ExampleInventoryRead.main()</code>, and so we
must catch <code class="classname">DatabaseException</code> because the <code class="literal">com.sleepycat.je.*</code>
APIs throw them.
</p>
<a id="je_cursor12"></a>
<pre class="programlisting"> private static void usage() {
System.out.println("ExampleInventoryRead [-h &lt;env directory&gt;]");
System.exit(0);
}
public static void main(String args[]) {
ExampleInventoryRead eir = new ExampleInventoryRead();
try {
eir.run(args);
} catch (DatabaseException dbe) {
System.err.println("ExampleInventoryRead: " + dbe.toString());
dbe.printStackTrace();
} finally {
myDbEnv.close();
}
System.out.println("All done.");
}</pre>
<p>In <code class="methodname">ExampleInventoryRead.run()</code>, we call <code class="methodname">MyDbEnv.setup()</code> to
open our environment and databases. Then we create the bindings that we need for using our data objects with
<code class="classname">DatabaseEntry</code> objects.
</p>
<a id="je_cursor13"></a>
<pre class="programlisting"> private void run(String args[]) throws DatabaseException {
// Parse the arguments list
parseArgs(args);
myDbEnv.setup(myDbEnvPath, // path to the environment home
true); // is this environment read-only?
// Setup our bindings.
inventoryBinding = new InventoryBinding();
vendorBinding =
new SerialBinding(myDbEnv.getClassCatalog(),
Vendor.class);
showAllInventory();
}</pre>
<p>Now we write the loop that displays the <code class="classname">Inventory</code>
records. We do this by opening a cursor on the inventory database and
iterating over all its contents, displaying each as we go.</p>
<a id="je_cursor14"></a>
<pre class="programlisting"> private void showAllInventory()
throws DatabaseException {
// Get a cursor
Cursor cursor = myDbEnv.getInventoryDB().openCursor(null, null);
// DatabaseEntry objects used for reading records
DatabaseEntry foundKey = new DatabaseEntry();
DatabaseEntry foundData = new DatabaseEntry();
try { // always want to make sure the cursor gets closed.
while (cursor.getNext(foundKey, foundData,
LockMode.DEFAULT) == OperationStatus.SUCCESS) {
Inventory theInventory =
(Inventory)inventoryBinding.entryToObject(foundData);
displayInventoryRecord(foundKey, theInventory);
}
} catch (Exception e) {
System.err.println("Error on inventory cursor:");
System.err.println(e.toString());
e.printStackTrace();
} finally {
cursor.close();
}
} </pre>
<p>We use <code class="methodname">ExampleInventoryRead.displayInventoryRecord()</code> to actually show the record. This
method first displays all the relevant information from the retrieved
Inventory object. It then uses the vendor database to retrieve and
display the vendor. Because the vendor database is keyed by vendor name,
and because each inventory object contains this key, it is trivial to
retrieve the appropriate vendor record.</p>
<a id="je_cursor15"></a>
<pre class="programlisting"> private void displayInventoryRecord(DatabaseEntry theKey,
Inventory theInventory)
throws DatabaseException {
DatabaseEntry searchKey = null;
try {
String theSKU = new String(theKey.getData(), "UTF-8");
System.out.println(theSKU + ":");
System.out.println("\t " + theInventory.getItemName());
System.out.println("\t " + theInventory.getCategory());
System.out.println("\t " + theInventory.getVendor());
System.out.println("\t\tNumber in stock: " +
theInventory.getVendorInventory());
System.out.println("\t\tPrice per unit: " +
theInventory.getVendorPrice());
System.out.println("\t\tContact: ");
searchKey =
new DatabaseEntry(theInventory.getVendor().getBytes("UTF-8"));
} catch (IOException willNeverOccur) {}
DatabaseEntry foundVendor = new DatabaseEntry();
if (myDbEnv.getVendorDB().get(null, searchKey, foundVendor,
LockMode.DEFAULT) != OperationStatus.SUCCESS) {
System.out.println("Could not find vendor: " +
theInventory.getVendor() + ".");
System.exit(-1);
} else {
Vendor theVendor =
(Vendor)vendorBinding.entryToObject(foundVendor);
System.out.println("\t\t " + theVendor.getAddress());
System.out.println("\t\t " + theVendor.getCity() + ", " +
theVendor.getState() + " " + theVendor.getZipcode());
System.out.println("\t\t Business Phone: " +
theVendor.getBusinessPhoneNumber());
System.out.println("\t\t Sales Rep: " +
theVendor.getRepName());
System.out.println("\t\t " +
theVendor.getRepPhoneNumber());
}
}</pre>
<p>The remainder of this application provides a utility method used
to parse the command line options. From the perspective of this
document, this is relatively uninteresting. You can see how this is
implemented by looking at:
</p>
<pre class="programlisting"><span class="emphasis"><em>JE_HOME</em></span>/examples/je/gettingStarted/ExampleInventoryRead.java</pre>
<p>
where <code class="literal"><span class="emphasis"><em>JE_HOME</em></span></code> is the location where you
placed your JE distribution.
</p>
</div>
</div>
<br class="example-break" />
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="ReplacingEntryWCursor.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="Cursors.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="indexes.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Replacing Records Using Cursors </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Chapter 10. Secondary Databases</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,119 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>DataAccessor.java</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="dpl_example.html" title="Chapter 6. A DPL Example" />
<link rel="prev" href="mydbenv-persist.html" title="MyDbEnv" />
<link rel="next" href="dpl_exampledatabaseput.html" title="ExampleDatabasePut.java" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">DataAccessor.java</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="mydbenv-persist.html">Prev</a> </td>
<th width="60%" align="center">Chapter 6. A DPL Example</th>
<td width="20%" align="right"> <a accesskey="n" href="dpl_exampledatabaseput.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="dataaccessorclass"></a>DataAccessor.java</h2>
</div>
</div>
</div>
<p>
Now that we have implemented our data classes,
we can write a class that will provide
convenient access to our primary and
secondary indexes.
Note that like our data classes, this class is shared by both our
example programs.
</p>
<p>
If you compare this class against our
<code class="classname">Vendor</code> and
<code class="classname">Inventory</code>
class implementations, you will see that the
primary and secondary indices declared there are
referenced by this class.
</p>
<p>
See <a class="xref" href="dpl_example.html#vendorclass" title="Vendor.java">Vendor.java</a>
and
<a class="xref" href="inventoryclass.html" title="Inventory.java">Inventory.java</a>
for those implementations.
</p>
<pre class="programlisting">package persist.gettingStarted;
import java.io.File;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.persist.EntityStore;
import com.sleepycat.persist.PrimaryIndex;
import com.sleepycat.persist.SecondaryIndex;
public class DataAccessor {
// Open the indices
public DataAccessor(EntityStore store)
throws DatabaseException {
// Primary key for Inventory classes
inventoryBySku = store.getPrimaryIndex(
String.class, Inventory.class);
// Secondary key for Inventory classes
// Last field in the getSecondaryIndex() method must be
// the name of a class member; in this case, an Inventory.class
// data member.
inventoryByName = store.getSecondaryIndex(
inventoryBySku, String.class, "itemName");
// Primary key for Vendor class
vendorByName = store.getPrimaryIndex(
String.class, Vendor.class);
}
// Inventory Accessors
PrimaryIndex&lt;String,Inventory&gt; inventoryBySku;
SecondaryIndex&lt;String,String,Inventory&gt; inventoryByName;
// Vendor Accessors
PrimaryIndex&lt;String,Vendor&gt; vendorByName;
} </pre>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="mydbenv-persist.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="dpl_example.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="dpl_exampledatabaseput.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">MyDbEnv </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> ExampleDatabasePut.java</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,546 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Chapter 7. Databases</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="baseapi.html" title="Part II. Programming with the Base API" />
<link rel="prev" href="baseapi.html" title="Part II. Programming with the Base API" />
<link rel="next" href="dbprops.html" title="Database Properties" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Chapter 7. Databases</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="baseapi.html">Prev</a> </td>
<th width="60%" align="center">Part II. Programming with the Base API</th>
<td width="20%" align="right"> <a accesskey="n" href="dbprops.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="chapter" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title"><a id="databases"></a>Chapter 7. Databases</h2>
</div>
</div>
</div>
<div class="toc">
<p>
<b>Table of Contents</b>
</p>
<dl>
<dt>
<span class="sect1">
<a href="databases.html#DBOpen">Opening Databases</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect2">
<a href="databases.html#dwdatabase">Deferred Write Databases</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="databases.html#tempdbje">Temporary Databases</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="databases.html#dbclose">Closing Databases</a>
</span>
</dt>
</dl>
</dd>
<dt>
<span class="sect1">
<a href="dbprops.html">Database Properties</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="DBAdmin.html">Administrative Methods</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="dbUsage.html">Database Example</a>
</span>
</dt>
</dl>
</div>
<p>In Berkeley DB Java Edition, a database is a collection of <span class="emphasis"><em>records</em></span>. Records,
in turn, consist of key/data pairings.
</p>
<p>
Conceptually, you can think of a
<code class="classname">Database</code>
as containing a two-column table where column 1 contains a key and column 2
contains data. Both the key and the data are managed using
<code class="classname">DatabaseEntry</code>
<span>class instances</span>
(see <a class="xref" href="DBEntry.html" title="Chapter 8. Database Records">Database Records</a> for details on this
<span>class</span>
).
So, fundamentally, using a JE
<code class="classname">Database</code>
involves putting, getting, and deleting database records, which in turns involves efficiently
managing information
<span>encapsulated by </span>
<code class="classname">DatabaseEntry</code>
<span>objects.</span>
The next several chapters of this book are dedicated to those activities.
</p>
<p>
Note that on disk, databases are stored in sequentially numerically
named log files in the directory where the opening
environment is located. JE log files are described
<a class="xref" href="backuprestore.html#databaselogs" title="Databases and Log Files">Databases and Log Files</a>.
</p>
<p>
Also, note that in the previous section of this book, <a class="xref" href="dpl.html" title="Part I. Programming with the Direct Persistence Layer">Programming with the Direct Persistence Layer</a>,
we described the DPL The DPL handles all database management
for you, including creating all primary and secondary databases as is
required by your application. That said, if you are using the DPL
you can access the underlying database for a given index if
necessary. See the Javadoc for the DPL for more information.
</p>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="DBOpen"></a>Opening Databases</h2>
</div>
</div>
</div>
<div class="toc">
<dl>
<dt>
<span class="sect2">
<a href="databases.html#dwdatabase">Deferred Write Databases</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="databases.html#tempdbje">Temporary Databases</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="databases.html#dbclose">Closing Databases</a>
</span>
</dt>
</dl>
</div>
<p>
You open a database by using the
<code class="methodname">Environment.openDatabase()</code>
method (environments are described in <a class="xref" href="env.html" title="Chapter 2. Database Environments">Database Environments</a>). This
method creates and returns a <code class="classname">Database</code>
object handle.
You must provide <code class="methodname">Environment.openDatabase()</code>
with a database name.
</p>
<p>
You can optionally provide <code class="methodname">Environment.openDatabase()</code>
with a <code class="classname">DatabaseConfig()</code> object.
<code class="classname">DatabaseConfig()</code> allows you to set properties for
the database, such as whether it can be created if it does not currently
exist, whether you are opening it read-only, and whether the database is to support transactions.
</p>
<p>
Note that by default, JE does not create databases if they do not already exist.
To override this behavior, set the <a class="link" href="dbprops.html" title="Database Properties">creation property</a> to true.
</p>
<p>
Finally, if you configured your environment and database to support transactions,
you can optionally provide a transaction object to the
<code class="methodname">Environment.openDatabase()</code>.
Transactions are described in the
<em class="citetitle">Berkeley DB, Java Edition Getting Started with Transaction Processing</em> guide.
</p>
<p>
The following code fragment illustrates a database open:
<span></span>
</p>
<a id="je_db1"></a>
<pre class="programlisting">package je.gettingStarted;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseConfig;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;
import java.io.File;
...
Environment myDbEnvironment = null;
Database myDatabase = null;
...
try {
// Open the environment. Create it if it does not already exist.
EnvironmentConfig envConfig = new EnvironmentConfig();
envConfig.setAllowCreate(true);
myDbEnvironment = new Environment(new File("/export/dbEnv"),
envConfig);
// Open the database. Create it if it does not already exist.
DatabaseConfig dbConfig = new DatabaseConfig();
dbConfig.setAllowCreate(true);
myDatabase = myDbEnvironment.openDatabase(null,
"sampleDatabase",
dbConfig);
} catch (DatabaseException dbe) {
// Exception handling goes here
}</pre>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="dwdatabase"></a>Deferred Write Databases</h3>
</div>
</div>
</div>
<p>
By default, JE database operations that modify the
database are written (logged) at the time of the operation. For transactional
databases, changes become durable when the transaction is committed.
</p>
<p>
However, deferred write databases operations are not written at the time
of the operation. Writing is deferred for as long as possible. The
changes are only guaranteed to be durable after the
<code class="methodname">Database.sync()</code> method
is called or the database is properly closed.
</p>
<p>
Deferring writes in this manner has two performance advantages when performing
database modifications:
</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>
When multiple threads are performing writes, Concurrency is increased
because the bottleneck of writing to the log is avoided.
</p>
</li>
<li>
<p>
Less total writing takes place. If a single record is modified more
than once, or modified and deleted, then only the final result must
be written. If a record is inserted and deleted before a
database sync or close occurs, nothing at all is written to disk.
The same advantage holds for writing internal index
information.
</p>
</li>
</ol>
</div>
<p>
Deferred write databases are useful for applications that perform a
great deal of database modifications, record additions, deletions, and
so forth. By delaying the data write, you delay the disk I/O. Depending
on your workload, this can improve your data throughput by quite a lot.
</p>
<p>
While the durability of a deferred write database is only
<span class="emphasis"><em>guaranteed</em></span> when
<code class="methodname">Database.sync()</code>
is called or the database is properly closed, writing may also occur at other times.
For example, a JE checkpoint will effectively perform a
<code class="methodname">Database.sync()</code> on all deferred
write databases that are open at the time of the checkpoint. If you are
using deferred write to load a large data set, and you want to reduce
writing as much as possible during the load, consider disabling the JE checkpointer.
</p>
<p>
Also, if the JE cache overflows as database modifications occur, information discarded
from the cache is written to disk in order to avoid losing the changes. If you wish to reduce this
writing to a minimum, configure your cache to be large enough to hold the entire
data set being modified, or as large as possible.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;">
<h3 class="title">Note</h3>
<p>
Despite the examples noted in the previous paragraphs, there is no guarantee that changes
to a deferred write database are durable unless <code class="methodname">Database.sync()</code>
is called or the database is closed. If you need guaranteed
durability for an operation, consider using transactions instead of deferred write.
</p>
</div>
<p>
You should also be aware that <code class="methodname">Database.sync()</code> is a
relatively expensive operation because all outstanding changes to the
database are written, including internal index information. If you find
that you are calling <code class="methodname">Database.sync()</code>
frequently, consider using transactions.
</p>
<p>
All other rules of behavior pertain to deferred write databases
as they do to normal databases. Deferred write databases must be
named and created just as you would a normal database. If you want to
delete the deferred write database, you must remove it just as
you would a normal database. This is true even if the deferred
write database is empty because its name persists in the
environment's namespace until such a time as the database is
removed.
</p>
<p>
Note that determining whether a database is deferred write is a
configuration option. It is therefore possible to switch a
database between "normal" mode and deferred write database. You
might want to do this if, for example, you want to load a lot
of data to the database. In this case, loading data to the
database while it is in deferred write state is faster than
in "normal" state, because you can avoid a lot of the normal disk
I/O overhead during the load process. Once the load is
complete, sync the database, close it, and and then reopen it
as a normal database. You can then continue operations
as if the database had been created as a "normal" database.
</p>
<p>
To configure a database as deferred write, set
<code class="methodname">DatabaseConfig.setDeferredWrite()</code>
to <code class="literal">true</code> and then open the database with
that <code class="classname">DatabaseConfig</code> option.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;">
<h3 class="title">Note</h3>
<p>
If you are using the DPL, then you configure your entire
store to be deferred write using
<code class="methodname">StoreConfig.setDeferredWrite()</code>.
You can also sync every database in your store using
<code class="methodname">EntityStore.sync()</code>.
</p>
</div>
<p>
For example, the following code fragment opens and closes a
deferred write database:
</p>
<pre class="programlisting">package je.gettingStarted;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseConfig;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;
import java.io.File;
...
Environment myDbEnvironment = null;
Database myDatabase = null;
...
try {
// Open the environment. Create it if it does not already exist.
EnvironmentConfig envConfig = new EnvironmentConfig();
envConfig.setAllowCreate(true);
myDbEnvironment = new Environment(new File("/export/dbEnv"),
envConfig);
// Open the database. Create it if it does not already exist.
DatabaseConfig dbConfig = new DatabaseConfig();
dbConfig.setAllowCreate(true);
// Make it deferred write
dbConfig.setDeferredWrite(true);
myDatabase = myDbEnvironment.openDatabase(null,
"sampleDatabase",
dbConfig);
...
// do work
...
// Do this when you want the work to be persistent at a
// specific point, prior to closing the database.
myDatabase.sync();
// then close the database and environment here
// (described later in this chapter).
} catch (DatabaseException dbe) {
// Exception handling goes here
}</pre>
</div>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="tempdbje"></a>Temporary Databases</h3>
</div>
</div>
</div>
<p>
By default, all JE databases are durable; that is, the data that you put in them
will remain in them across program runs, unless you explicitly delete the data.
However, it is possible to configure a
<span class="emphasis"><em>temporary</em></span> database that is not durable. A temporary database is
automatically deleted when it is closed or after a crash occurs.
</p>
<p>
Temporary databases are essentially in-memory only databases. Therefore,
they are particularly useful for applications that want databases which
are truly temporary.
</p>
<p>
Note that temporary databases do not always avoid disk I/O. It is particularly
important to realize that temporary databases can page to disk if the cache is not
large enough to hold the database's entire contents. Therefore, temporary database
performance is best when your in-memory cache is large enough to hold the database's
entire data-set.
</p>
<p>
A temporary database operates internally in deferred write mode and has
the same performance advantages as described above for deferred write
databases (see <a class="xref" href="databases.html#dwdatabase" title="Deferred Write Databases">Deferred Write Databases</a>).
However, unlike deferred write databases, a temporary database is not written
during checkpoints and this provides an additional performance advantage.
</p>
<p>
Temporary databases must be named and created just as you would a normal database.
To configure a database as temporary, set
<code class="methodname">DatabaseConfig.setTemporary</code> to
<code class="literal">true</code> and then open the database with that
<code class="classname">DatabaseConfig</code> instance.
</p>
<p>
For example:
</p>
<pre class="programlisting">package je.gettingStarted;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseConfig;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;
import java.io.File;
...
Environment myDbEnvironment = null;
Database myDatabase = null;
...
try {
// Open the environment. Create it if it does not already exist.
EnvironmentConfig envConfig = new EnvironmentConfig();
envConfig.setAllowCreate(true);
myDbEnvironment = new Environment(new File("/export/dbEnv"),
envConfig);
// Open the database. Create it if it does not already exist.
DatabaseConfig dbConfig = new DatabaseConfig();
dbConfig.setAllowCreate(true);
// Make it a temporary database
dbConfig.setTemporary(true);
myDatabase = myDbEnvironment.openDatabase(null,
"sampleDatabase",
dbConfig);
...
// do work
...
// then close the database and environment here
// (see the next section)
} catch (DatabaseException dbe) {
// Exception handling goes here
}</pre>
</div>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="dbclose"></a>Closing Databases</h3>
</div>
</div>
</div>
<p>Once you are done using the database, you must close it. You use the
<code class="methodname">Database.close()</code> method to do this.</p>
<p>Closing a database causes it to become unusable until it is opened
again. If any cursors are opened for the database,
JE warns you about the open cursors, and then closes them for you.
Active cursors during a database
close can cause unexpected results, especially if any of those cursors are
writing to the database in another thread. You should always make sure that all your
database accesses have completed before closing your database.</p>
<p>It is recommended that you close all your
databases before closing the environment to which they belong.</p>
<p>Cursors are described in <a class="xref" href="Cursors.html" title="Chapter 9. Using Cursors">Using Cursors</a> later in this manual.</p>
<p>
The following illustrates database and environment close:
</p>
<a id="je_db2"></a>
<pre class="programlisting">import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Database;
import com.sleepycat.je.Environment;
...
try {
if (myDatabase != null) {
myDatabase.close();
}
if (myDbEnvironment != null) {
myDbEnvironment.close();
}
} catch (DatabaseException dbe) {
// Exception handling goes here
} </pre>
</div>
</div>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="baseapi.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="baseapi.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="dbprops.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Part II. Programming with the Base API </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Database Properties</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,203 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Database Example</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="databases.html" title="Chapter 7. Databases" />
<link rel="prev" href="DBAdmin.html" title="Administrative Methods" />
<link rel="next" href="DBEntry.html" title="Chapter 8. Database Records" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Database Example</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="DBAdmin.html">Prev</a> </td>
<th width="60%" align="center">Chapter 7. Databases</th>
<td width="20%" align="right"> <a accesskey="n" href="DBEntry.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="dbUsage"></a>Database Example</h2>
</div>
</div>
</div>
<p>In <a class="xref" href="dbenvUsageExample.html" title="Database Environment Management Example">Database Environment Management Example</a> we created a class that manages an
<code class="classname">Environment</code>. We now extend that class to allow it
to open and manage multiple databases. Again, remember that you can find
this class in:
</p>
<pre class="programlisting"><span class="emphasis"><em>JE_HOME</em></span>/je/gettingStarted/MyDbEnv.java</pre>
<p>
where <code class="literal"><span class="emphasis"><em>JE_HOME</em></span></code> is the location where you
placed your JE distribution.
</p>
<div class="example">
<a id="mydbenvWDatabase"></a>
<p class="title">
<b>Example 7.1 Database Management with MyDbEnv</b>
</p>
<div class="example-contents">
<p>First, we need to import a few additional classes, and setup some global variables to support databases.
The databases that we are configuring and creating here are used by applications developed in examples later in this guide.</p>
<a id="je_db10"></a>
<pre class="programlisting">// File MyDbEnv.java
package je.gettingStarted;
import com.sleepycat.je.DatabaseException;
<strong class="userinput"><code>import com.sleepycat.je.DatabaseConfig;
import com.sleepycat.je.Database; </code></strong>
import com.sleepycat.je.EnvironmentConfig;
import com.sleepycat.je.Environment;
import java.io.File;
public class MyDbEnv {
private Environment myEnv;
<strong class="userinput"><code>private Database vendorDb;
private Database inventoryDb;</code></strong>
public MyDbEnv() {} </pre>
<p>
Next we need to update the <code class="methodname">MyDbEnv.setup()</code> method to instantiate a
<code class="classname">DatabaseConfig</code> object. We also need to set some properties on that object. These property
values are determined by the value of the <code class="literal">readOnly</code> parameter. We want our databases to be
read-only if the environment is also read-only. We also want to allow our databases to be created if the databases
are not read-only.
</p>
<a id="je_db11"></a>
<pre class="programlisting"> public void setup(File envHome, boolean readOnly)
throws DatabaseException {
// Instantiate an environment <strong class="userinput"><code>and database</code></strong> configuration object
EnvironmentConfig myEnvConfig = new EnvironmentConfig();
<strong class="userinput"><code>DatabaseConfig myDbConfig = new DatabaseConfig();</code></strong>
// Configure the environment <strong class="userinput"><code>and databases</code></strong> for the read-only
// state as identified by the readOnly parameter on this
// method call.
myEnvConfig.setReadOnly(readOnly);
<strong class="userinput"><code>myDbConfig.setReadOnly(readOnly);</code></strong>
// If the environment is opened for write, then we want to be
// able to create the environment <strong class="userinput"><code>and databases</code></strong> if
// they do not exist.
myEnvConfig.setAllowCreate(!readOnly);
<strong class="userinput"><code>myDbConfig.setAllowCreate(!readOnly);</code></strong>
// Instantiate the Environment. This opens it and also possibly
// creates it.
myEnv = new Environment(envHome, myEnvConfig);
<strong class="userinput"><code>// Now create and open our databases.
vendorDb = myEnv.openDatabase(null,
"VendorDB",
myDbConfig);
inventoryDb = myEnv.openDatabase(null,
"InventoryDB",
myDbConfig);</code></strong>
} </pre>
<p>
Next we need some additional getter methods used to return our database handles.
</p>
<a id="je_db12"></a>
<pre class="programlisting"> // Getter methods
public Environment getEnvironment() {
return myEnv;
}
<strong class="userinput"><code>public Database getVendorDB() {
return vendorDb;
}
public Database getInventoryDB() {
return inventoryDb;
}</code></strong> </pre>
<p>
Finally, we need to update the <code class="methodname">MyDbEnv.close()</code> method to close our databases.
</p>
<a id="je_db13"></a>
<pre class="programlisting"> // Close the environment
public void close() {
if (myEnv != null) {
try {
<strong class="userinput"><code>vendorDb.close();
inventoryDb.close();</code></strong>
myEnv.close();
} catch(DatabaseException dbe) {
System.err.println("Error closing MyDbEnv: " +
dbe.toString());
System.exit(-1);
}
}
}
}</pre>
<p>We can now use <code class="classname">MyDbEnv</code> to open and close
both database environments and databases from the appropriate place in
our application. For example:</p>
<a id="je_db14"></a>
<pre class="programlisting">package je.gettingStarted;
import com.sleepycat.je.DatabaseException;
<strong class="userinput"><code>import com.sleepycat.je.Database;</code></strong>
import java.io.File;
...
MyDbEnv exampleDbEnv = new MyDbEnv();
try {
exampleDbEnv.setup(new File("/directory/currently/exists"), true);
<strong class="userinput"><code>Database vendorDb = exampleDbEnv.getVendorDB();
Database inventoryDB = exampleDbEnv.getInventoryDB();</code></strong>
...
} catch(DatabaseException dbe) {
// Error code goes here
} finally {
exampleDbEnv.close();
} </pre>
</div>
</div>
<br class="example-break" />
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="DBAdmin.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="databases.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="DBEntry.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Administrative Methods </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Chapter 8. Database Records</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,180 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Database Environment Management Example</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="env.html" title="Chapter 2. Database Environments" />
<link rel="prev" href="envStats.html" title="Environment Statistics" />
<link rel="next" href="dpl.html" title="Part I. Programming with the Direct Persistence Layer" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Database Environment Management Example</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="envStats.html">Prev</a> </td>
<th width="60%" align="center">Chapter 2. Database Environments</th>
<td width="20%" align="right"> <a accesskey="n" href="dpl.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="dbenvUsageExample"></a>Database Environment Management Example</h2>
</div>
</div>
</div>
<p>
This example provides a complete class that can open and close an environment. It is
both extended and used in subsequent examples in this book to open and close both
environments and databases. We do this so as to make the example code
shorter and easier to manage. You can find this class in:
</p>
<pre class="programlisting"><span class="emphasis"><em>JE_HOME</em></span>/examples/je/gettingStarted/MyDbEnv.java</pre>
<p>
where <code class="literal"><span class="emphasis"><em>JE_HOME</em></span></code> is the location where you
placed your JE distribution.
</p>
<div class="example">
<a id="mydbenv"></a>
<p class="title">
<b>Example 2.1 Database Environment Management Class</b>
</p>
<div class="example-contents">
<p>First we write the normal class declarations. We also set up some
private data members that are used to manage environment creation. We
use the class constructor to instantiate the <code class="classname">EnvironmentConfig</code>
object that is used to configure our environment when we open it.</p>
<a id="je_env6"></a>
<pre class="programlisting">// File MyDbEnv.java
package je.gettingStarted;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;
import java.io.File;
public class MyDbEnv {
private Environment myEnv;
public MyDbEnv() {} </pre>
<p>Next we need a method to open the environment. This is responsible
for instantiating our <code class="classname">Environment</code> object.
Remember that instantiation is what opens the environment (or creates it
if the creation property is set to <code class="literal">true</code> and the
environment does not currently exist).
</p>
<a id="je_env7"></a>
<pre class="programlisting"> public void setup(File envHome, boolean readOnly)
throws DatabaseException {
// Instantiate an environment configuration object
EnvironmentConfig myEnvConfig = new EnvironmentConfig();
// Configure the environment for the read-only state as identified
// by the readOnly parameter on this method call.
myEnvConfig.setReadOnly(readOnly);
// If the environment is opened for write, then we want to be
// able to create the environment if it does not exist.
myEnvConfig.setAllowCreate(!readOnly);
// Instantiate the Environment. This opens it and also possibly
// creates it.
myEnv = new Environment(envHome, myEnvConfig);
} </pre>
<p>
Next we provide a getter method that allows us to retrieve the
<code class="classname">Environment</code> directly. This is needed for later
examples in this guide.
</p>
<a id="je_env8"></a>
<pre class="programlisting"> // Getter methods
public Environment getEnv() {
return myEnv;
} </pre>
<p>Finally, we need a method to close our <code class="classname">Environment</code>.
We wrap this operation in a <code class="literal">try</code> block so that it can
be used gracefully in a <code class="literal">finally</code> statement.</p>
<a id="je_env9"></a>
<pre class="programlisting"> // Close the environment
public void close() {
if (myEnv != null) {
try {
myEnv.close();
} catch(DatabaseException dbe) {
System.err.println("Error closing environment" +
dbe.toString());
}
}
}
} </pre>
<p>
This completes the <code class="classname">MyDbEnv</code> class. While not particularly useful
as it currently exists, we will build upon it throughout this book so that it will
eventually open and close all of the entity stores or databases required by our
applications.
</p>
<p>
We can now use <code class="classname">MyDbEnv</code> to open and close a database environment
from the appropriate place in our application. For example:
</p>
<a id="je_env10"></a>
<pre class="programlisting">package je.gettingStarted;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.DatabaseException;
import java.io.File;
...
MyDbEnv exampleDbEnv = new MyDbEnv();
try {
exampleDbEnv.setup(new File("/directory/currently/exists"), true);
...
} catch(DatabaseException dbe) {
// Error code goes here
} finally {
exampleDbEnv.close();
} </pre>
</div>
</div>
<br class="example-break" />
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="envStats.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="env.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="dpl.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Environment Statistics </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Part I. Programming with the Direct Persistence Layer</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,164 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Database Properties</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="databases.html" title="Chapter 7. Databases" />
<link rel="prev" href="databases.html" title="Chapter 7. Databases" />
<link rel="next" href="DBAdmin.html" title="Administrative Methods" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Database Properties</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="databases.html">Prev</a> </td>
<th width="60%" align="center">Chapter 7. Databases</th>
<td width="20%" align="right"> <a accesskey="n" href="DBAdmin.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="dbprops"></a>Database Properties</h2>
</div>
</div>
</div>
<p>You can set database properties using the <code class="classname">DatabaseConfig</code>
class. For each of the properties that you can set, there is a
corresponding getter method. Also, you can always retrieve the
<code class="classname">DatabaseConfig</code> object used by your database using
the <code class="methodname">Database.getConfig()</code> method.</p>
<p>The database properties that you can set are:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>
<code class="methodname">DatabaseConfig.setAllowCreate()</code>
</p>
<p>If <code class="literal">true</code>, the database is created when it is
opened. If false, the database open fails if the database does not
exist. This property has no meaning if the database currently exists.
Default is <code class="literal">false</code>.</p>
</li>
<li>
<p>
<code class="methodname">DatabaseConfig.setBtreeComparator()</code>
</p>
<p>Sets the class that is used to compare the keys found on two
database records. This class is used to determine the sort order for
two records in the database. By default, byte for byte comparison is
used.
For more information, see
<span><a class="xref" href="comparator.html" title="Using Comparators">Using Comparators</a>.</span>
</p>
</li>
<li>
<p>
<code class="methodname">DatabaseConfig.setDuplicateComparator()</code>
</p>
<p>
Sets the class that is used to compare two duplicate records in
the database. For more information, see
<span><a class="xref" href="comparator.html" title="Using Comparators">Using Comparators</a>.</span>
</p>
</li>
<li>
<p>
<code class="methodname">DatabaseConfig.setSortedDuplicates()</code>
</p>
<p>If <code class="literal">true</code>, duplicate records are allowed in the
database. If this value is <code class="literal">false</code>, then putting a duplicate record into the database
results in an error return from the put call.
Note that this property can be set only at database creation time. Default is <code class="literal">false</code>.
</p>
<p>
Note that your database must not support duplicates if it is to be associated with one or more
secondary indices. Secondaries are described in <a class="xref" href="indexes.html" title="Chapter 10. Secondary Databases">Secondary Databases</a>.
</p>
</li>
<li>
<p>
<code class="methodname">DatabaseConfig.setExclusiveCreate()</code>
</p>
<p>If <code class="literal">true</code>, the database open fails if the
database currently exists. That is, the open must result in the
creation of a new database. Default is <code class="literal">false</code>.</p>
</li>
<li>
<p>
<code class="methodname">DatabaseConfig.setReadOnly()</code>
</p>
<p>If true, the database is opened for read activities only.
Default is <code class="literal">false</code>.</p>
</li>
<li>
<p>
<code class="methodname">DatabaseConfig.setTransactional()</code>
</p>
<p>If true, the database supports transactions.
Default is <code class="literal">false</code>. Note that a database cannot support
transactions if the environment is non-transactional.</p>
</li>
</ul>
</div>
<p>For example:</p>
<a id="je_db3"></a>
<pre class="programlisting">package je.gettingStarted;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseConfig;
...
// Environment open omitted for brevity
...
Database myDatabase = null;
try {
DatabaseConfig dbConfig = new DatabaseConfig();
dbConfig.setAllowCreate(true);
dbConfig.setSortedDuplicates(true);
myDatabase =
myDbEnv.openDatabase(null,
"sampleDatabase",
dbConfig);
} catch (DatabaseException dbe) {
// Exception handling goes here.
}</pre>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="databases.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="databases.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="DBAdmin.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Chapter 7. Databases </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Administrative Methods</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,693 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Database Record Example</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="DBEntry.html" title="Chapter 8. Database Records" />
<link rel="prev" href="comparator.html" title="Using Comparators" />
<link rel="next" href="Cursors.html" title="Chapter 9. Using Cursors" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Database Record Example</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="comparator.html">Prev</a> </td>
<th width="60%" align="center">Chapter 8. Database Records</th>
<td width="20%" align="right"> <a accesskey="n" href="Cursors.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="dbtUsage"></a>Database Record Example</h2>
</div>
</div>
</div>
<p>In <a class="xref" href="dbUsage.html" title="Database Example">Database Example</a>, we created
<code class="classname">MyDbEnv</code>, a class that manages
<code class="classname">DatabaseEnvironment</code> and <code class="classname">Database</code>
opens and closes. We will now write an application that takes advantage of
this class to open databases, put a series of records in them, and then
close the databases and environment.</p>
<p>Remember that all of the classes and programs presented here can be
found in the following directory:
</p>
<pre class="programlisting"><span class="emphasis"><em>JE_HOME</em></span>/examples/je/gettingStarted</pre>
<p>
where <code class="literal"><span class="emphasis"><em>JE_HOME</em></span></code> is the location where you
placed your JE distribution.
</p>
<p>Note that in this example, we are going to save two types of
information. First there are a series of inventory records that identify
information about some food items (fruits, vegetables, and desserts).
These records identify particulars about each item such as the vendor that
the item can be obtained from, how much the vendor has in stock, the price
per unit, and so forth.</p>
<p>
We also want to manage vendor contact information, such as the
vendor's address and phone number, the sales representative's name
and his phone number, and so forth.
</p>
<div class="example">
<a id="inventory"></a>
<p class="title">
<b>Example 8.1 Inventory.java</b>
</p>
<div class="example-contents">
<p>
All Inventory data is encapsulated in an instance of the following
class. Note that because this class is not serializable, we need a
custom tuple binding in order to place it on a <code class="classname">DatabaseEntry</code>
object. Because the <code class="classname">TupleInput</code> and
<code class="classname">TupleOutput</code> classes used by custom tuple bindings
support Java numerical types and not Java numerical classes, we use
<code class="literal">int</code> and <code class="literal">float</code> here instead of the
corresponding <code class="classname">Integer</code> and <code class="classname">Float</code>
classes.
</p>
<a id="je_dbt16"></a>
<pre class="programlisting">// File Inventory.java
package je.gettingStarted;
public class Inventory {
private String sku;
private String itemName;
private String category;
private String vendor;
private int vendorInventory;
private float vendorPrice;
public void setSku(String data) {
sku = data;
}
public void setItemName(String data) {
itemName = data;
}
public void setCategory(String data) {
category = data;
}
public void setVendorInventory(int data) {
vendorInventory = data;
}
public void setVendor(String data) {
vendor = data;
}
public void setVendorPrice(float data) {
vendorPrice = data;
}
public String getSku() { return sku; }
public String getItemName() { return itemName; }
public String getCategory() { return category; }
public int getVendorInventory() { return vendorInventory; }
public String getVendor() { return vendor; }
public float getVendorPrice() { return vendorPrice; }
} </pre>
</div>
</div>
<br class="example-break" />
<div class="example">
<a id="vendor"></a>
<p class="title">
<b>Example 8.2 Vendor.java</b>
</p>
<div class="example-contents">
<p>
The data for vendor records are stored in instances of the following
class. Notice that we are using serialization with this class simply
to demonstrate serializing a class instance.
</p>
<a id="je_dbt17"></a>
<pre class="programlisting">// File Vendor.java
package je.gettingStarted;
import java.io.Serializable;
public class Vendor implements Serializable {
private String repName;
private String address;
private String city;
private String state;
private String zipcode;
private String bizPhoneNumber;
private String repPhoneNumber;
private String vendor;
public void setRepName(String data) {
repName = data;
}
public void setAddress(String data) {
address = data;
}
public void setCity(String data) {
city = data;
}
public void setState(String data) {
state = data;
}
public void setZipcode(String data) {
zipcode = data;
}
public void setBusinessPhoneNumber(String data) {
bizPhoneNumber = data;
}
public void setRepPhoneNumber(String data) {
repPhoneNumber = data;
}
public void setVendorName(String data) {
vendor = data;
}
...
// Corresponding getter methods omitted for brevity.
// See examples/je/gettingStarted/Vendor.java
// for a complete implementation of this class.
} </pre>
</div>
</div>
<br class="example-break" />
<p>
Because we will not be using serialization to convert our
<code class="classname">Inventory</code> objects to a <code class="classname">DatabaseEntry</code>
object, we need a custom tuple binding:
</p>
<div class="example">
<a id="InventoryBinding"></a>
<p class="title">
<b>Example 8.3 InventoryBinding.java</b>
</p>
<div class="example-contents">
<a id="je_dbt18"></a>
<pre class="programlisting">// File InventoryBinding.java
package je.gettingStarted;
import com.sleepycat.bind.tuple.TupleBinding;
import com.sleepycat.bind.tuple.TupleInput;
import com.sleepycat.bind.tuple.TupleOutput;
public class InventoryBinding extends TupleBinding {
// Implement this abstract method. Used to convert
// a DatabaseEntry to an Inventory object.
public Object entryToObject(TupleInput ti) {
String sku = ti.readString();
String itemName = ti.readString();
String category = ti.readString();
String vendor = ti.readString();
int vendorInventory = ti.readInt();
float vendorPrice = ti.readFloat();
Inventory inventory = new Inventory();
inventory.setSku(sku);
inventory.setItemName(itemName);
inventory.setCategory(category);
inventory.setVendor(vendor);
inventory.setVendorInventory(vendorInventory);
inventory.setVendorPrice(vendorPrice);
return inventory;
}
// Implement this abstract method. Used to convert a
// Inventory object to a DatabaseEntry object.
public void objectToEntry(Object object, TupleOutput to) {
Inventory inventory = (Inventory)object;
to.writeString(inventory.getSku());
to.writeString(inventory.getItemName());
to.writeString(inventory.getCategory());
to.writeString(inventory.getVendor());
to.writeInt(inventory.getVendorInventory());
to.writeFloat(inventory.getVendorPrice());
}
} </pre>
</div>
</div>
<br class="example-break" />
<p>In order to store the data identified above, we write the
<code class="classname">ExampleDatabasePut</code> application. This application
loads the inventory and vendor databases for you.</p>
<p>Inventory information is stored in a <code class="classname">Database</code>
dedicated for that purpose. The key for each such record is a product SKU.
The inventory data stored in this database are objects of the
<code class="classname">Inventory</code> class (see <a class="xref" href="dbtUsage.html#inventory" title="Example 8.1 Inventory.java">Inventory.java</a> for more information).
<code class="classname">ExampleDatabasePut</code> loads the inventory database
as follows:</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>Reads the inventory data from a flat text file prepared in
advance for this purpose.</p>
</li>
<li>
<p>Uses <code class="classname">java.lang.String</code> to create a key
based on the item's SKU.</p>
</li>
<li>
<p>Uses an <code class="classname">Inventory</code> class instance for the
record data. This object is stored on a <code class="classname">DatabaseEntry</code>
object using <code class="classname">InventoryBinding</code>, a custom tuple
binding that we implemented above.</p>
</li>
<li>
<p>Saves each record to the inventory database.</p>
</li>
</ol>
</div>
<p>Vendor information is also stored in a <code class="classname">Database</code>
dedicated for that purpose. The vendor data stored in this database are objects of the
<code class="classname">Vendor</code> class (see <a class="xref" href="dbtUsage.html#vendor" title="Example 8.2 Vendor.java">Vendor.java</a> for more information). To load this
<code class="classname">Database</code>, <code class="classname">ExampleDatabasePut</code>
does the following:</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>Reads the vendor data from a flat text file prepared in advance
for this purpose.</p>
</li>
<li>
<p>Uses the vendor's name as the record's key.</p>
</li>
<li>
<p>Uses a <code class="classname">Vendor</code> class instance for the
record data. This object is stored on a <code class="classname">DatabaseEntry</code>
object using <code class="classname">com.sleepycat.bind.serial.SerialBinding</code>.</p>
</li>
</ol>
</div>
<div class="example">
<a id="dbenvStoredClass"></a>
<p class="title">
<b>Example 8.4 Stored Class Catalog Management with MyDbEnv</b>
</p>
<div class="example-contents">
<p>
Before we can write <code class="classname">ExampleDatabasePut</code>, we need to update
<code class="filename">MyDbEnv.java</code> to support the class catalogs that we need for this application.
</p>
<p>
To do this, we start by importing an additional class to support stored class catalogs:
</p>
<a id="je_dbt19"></a>
<pre class="programlisting">// File MyDbEnv.java
package je.gettingStarted;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseConfig;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.EnvironmentConfig;
import com.sleepycat.je.Environment;
import java.io.File;
<strong class="userinput"><code>import com.sleepycat.bind.serial.StoredClassCatalog;</code></strong> </pre>
<p>
We also need to add two additional private data members to this class. One supports the database used for the class
catalog, and the other is used as a handle for the class catalog itself.
</p>
<a id="je_dbt20"></a>
<pre class="programlisting">public class MyDbEnv {
private Environment myEnv;
private Database vendorDb;
private Database inventoryDb;
<strong class="userinput"><code>private Database classCatalogDb;
// Needed for object serialization
private StoredClassCatalog classCatalog;</code></strong>
public MyDbEnv() {} </pre>
<p>
Next we need to update the <code class="methodname">MyDbEnv.setup()</code> method to open the class catalog database and
create the class catalog.
</p>
<a id="je_dbt21"></a>
<pre class="programlisting"> public void setup(File envHome, boolean readOnly)
throws DatabaseException {
...
// Database and environment configuration omitted for brevity
...
// Instantiate the Environment. This opens it and also possibly
// creates it.
myEnv = new Environment(envHome, myEnvConfig);
// Now create and open our databases.
vendorDb = myEnv.openDatabase(null, "VendorDB", myDbConfig);
inventoryDb = myEnv.openDatabase(null, "InventoryDB", myDbConfig);
<strong class="userinput"><code>// Open the class catalog db. This is used to
// optimize class serialization.
classCatalogDb =
myEnv.openDatabase(null,
"ClassCatalogDB",
myDbConfig);
// Create our class catalog
classCatalog = new StoredClassCatalog(classCatalogDb);</code></strong>
} </pre>
<p>
Next we need a getter method to return the class catalog. Note that we do not provide a getter for
the catalog database itself our application has no need for that.
</p>
<a id="je_dbt22"></a>
<pre class="programlisting">// Getter methods
public Environment getEnvironment() {
return myEnv;
}
public Database getVendorDB() {
return vendorDb;
}
public Database getInventoryDB() {
return inventoryDb;
}
<strong class="userinput"><code>public StoredClassCatalog getClassCatalog() {
return classCatalog;
}</code></strong> </pre>
<p>
Finally, we need to update the <code class="methodname">MyDbEnv.close()</code> method to close the
class catalog database.
</p>
<a id="je_dbt23"></a>
<pre class="programlisting"> // Close the environment
public void close() {
if (myEnv != null) {
try {
vendorDb.close();
inventoryDb.close();
<strong class="userinput"><code>classCatalogDb.close()</code></strong>
myEnv.close();
} catch(DatabaseException dbe) {
System.err.println("Error closing MyDbEnv: " +
dbe.toString());
System.exit(-1);
}
}
}
}</pre>
</div>
</div>
<br class="example-break" />
<p>
So far we have identified the data that we want to store in our
databases and how we will convert that data in and out of
<code class="classname">DatabaseEntry</code> objects for database storage. We
have also updated <code class="classname">MyDbEnv</code> to manage our databases
for us. Now we write <code class="classname">ExampleDatabasePut</code> to
actually put the inventory and vendor data into their respective
databases. Because of the work that we have done so far, this
application is actually fairly simple to write.
</p>
<div class="example">
<a id="EDP"></a>
<p class="title">
<b>Example 8.5 ExampleDatabasePut.java</b>
</p>
<div class="example-contents">
<p>First we need the usual series of import statements:</p>
<a id="je_dbt24"></a>
<pre class="programlisting">//File ExampleDatabasePut.java
package je.gettingStarted;
// Bind classes used to move class objects in an out of byte arrays.
import com.sleepycat.bind.EntryBinding;
import com.sleepycat.bind.serial.SerialBinding;
import com.sleepycat.bind.tuple.TupleBinding;
// Standard JE database imports
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.DatabaseException;
// Most of this is used for loading data from a text file for storage
// in the databases.
import java.io.File;
import java.io.FileInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;</pre>
<p>Next comes the class declaration and the private data members that
we need for this class. Most of these are setting up default values for
the program.</p>
<p>Note that two <code class="classname">DatabaseEntry</code> objects are
instantiated here. We will reuse these for every database operation that
this program performs. Also a <code class="classname">MyDbEnv</code> object is
instantiated here. We can do this because its constructor never throws
an exception. See <a class="xref" href="dbtUsage.html#dbenvStoredClass" title="Example 8.4 Stored Class Catalog Management with MyDbEnv">Stored Class Catalog Management with MyDbEnv</a> for
its implementation details.</p>
<p>Finally, the <code class="filename">inventory.txt</code> and
<code class="filename">vendors.txt</code> file can be found in the GettingStarted
examples directory along with the classes described in this extended
example.</p>
<a id="je_dbt25"></a>
<pre class="programlisting">public class ExampleDatabasePut {
private static File myDbEnvPath = new File("/tmp/JEDB");
private static File inventoryFile = new File("./inventory.txt");
private static File vendorsFile = new File("./vendors.txt");
// DatabaseEntries used for loading records
private static DatabaseEntry theKey = new DatabaseEntry();
private static DatabaseEntry theData = new DatabaseEntry();
// Encapsulates the environment and databases.
private static MyDbEnv myDbEnv = new MyDbEnv();</pre>
<p>
Next comes the <code class="methodname">usage()</code> and
<code class="methodname">main()</code> methods. Notice the exception handling
in the <code class="methodname">main()</code> method. This is the only place in the application where we
catch exceptions. For this reason, we must catch
<code class="classname">DatabaseException</code> which is thrown by the
<code class="literal">com.sleepycat.je.*</code> classes.
</p>
<p>Also notice the call to <code class="methodname">MyDbEnv.close()</code>
in the <code class="literal">finally</code> block. This is the only place in the
application where <code class="methodname">MyDbEnv.close()</code> is called.
<code class="methodname">MyDbEnv.close()</code> is responsible for closing the
<code class="classname">Environment</code> and all open <code class="classname">Database</code>
handles for you.</p>
<a id="je_dbt26"></a>
<pre class="programlisting"> private static void usage() {
System.out.println("ExampleDatabasePut [-h &lt;env directory&gt;]");
System.out.println(" [-s &lt;selections file&gt;]");
System.out.println(" [-v &lt;vendors file&gt;]");
System.exit(-1);
}
public static void main(String args[]) {
ExampleDatabasePut edp = new ExampleDatabasePut();
try {
edp.run(args);
} catch (DatabaseException dbe) {
System.err.println("ExampleDatabasePut: " + dbe.toString());
dbe.printStackTrace();
} catch (Exception e) {
System.err.println("Exception: " + e.toString());
e.printStackTrace();
} finally {
myDbEnv.close();
}
System.out.println("All done.");
} </pre>
<p>Next we write the <code class="methodname">ExampleDatabasePut.run()</code>
method. This method is responsible for initializing all objects.
Because our environment and databases are all opened using the
<code class="methodname">MyDbEnv.setup()</code> method, <code class="methodname">ExampleDatabasePut.run()</code>
method is only responsible for calling <code class="methodname">MyDbEnv.setup()</code> and then calling
the <code class="classname">ExampleDatabasePut</code> methods that actually load the databases.
</p>
<a id="je_dbt27"></a>
<pre class="programlisting"> private void run(String args[]) throws DatabaseException {
// Parse the arguments list
parseArgs(args);
myDbEnv.setup(myDbEnvPath, // path to the environment home
false); // is this environment read-only?
System.out.println("loading vendors db.");
loadVendorsDb();
System.out.println("loading inventory db.");
loadInventoryDb();
} </pre>
<p>This next method loads the vendor database. This method
uses serialization to convert the <code class="classname">Vendor</code> object
to a <code class="classname">DatabaseEntry</code> object.</p>
<a id="je_dbt28"></a>
<pre class="programlisting"> private void loadVendorsDb()
throws DatabaseException {
// loadFile opens a flat-text file that contains our data
// and loads it into a list for us to work with. The integer
// parameter represents the number of fields expected in the
// file.
List&lt;String[]&gt; vendors = loadFile(vendorsFile, 8);
// Now load the data into the database. The vendor's name is the
// key, and the data is a Vendor class object.
// Need a serial binding for the data
EntryBinding dataBinding =
new SerialBinding(myDbEnv.getClassCatalog(), Vendor.class);
for (int i = 0; i &lt; vendors.size(); i++) {
String[] sArray = vendors.get(i);
Vendor theVendor = new Vendor();
theVendor.setVendorName(sArray[0]);
theVendor.setAddress(sArray[1]);
theVendor.setCity(sArray[2]);
theVendor.setState(sArray[3]);
theVendor.setZipcode(sArray[4]);
theVendor.setBusinessPhoneNumber(sArray[5]);
theVendor.setRepName(sArray[6]);
theVendor.setRepPhoneNumber(sArray[7]);
// The key is the vendor's name.
// ASSUMES THE VENDOR'S NAME IS UNIQUE!
String vendorName = theVendor.getVendorName();
try {
theKey = new DatabaseEntry(vendorName.getBytes("UTF-8"));
} catch (IOException willNeverOccur) {}
// Convert the Vendor object to a DatabaseEntry object
// using our SerialBinding
dataBinding.objectToEntry(theVendor, theData);
// Put it in the database. These puts are transactionally
// protected (we're using autocommit).
myDbEnv.getVendorDB().put(null, theKey, theData);
}
} </pre>
<p>Now load the inventory database. This method uses our
custom tuple binding (see <a class="xref" href="dbtUsage.html#InventoryBinding" title="Example 8.3 InventoryBinding.java">InventoryBinding.java</a>) to convert the <code class="classname">Inventory</code>
object to a <code class="classname">DatabaseEntry</code> object.</p>
<a id="je_dbt29"></a>
<pre class="programlisting"> private void loadInventoryDb()
throws DatabaseException {
// loadFile opens a flat-text file that contains our data
// and loads it into a list for us to work with. The integer
// parameter represents the number of fields expected in the
// file.
List&lt;String[]&gt; inventoryArray = loadFile(inventoryFile, 6);
// Now load the data into the database. The item's sku is the
// key, and the data is an Inventory class object.
// Need a tuple binding for the Inventory class.
TupleBinding inventoryBinding = new InventoryBinding();
for (int i = 0; i &lt; inventoryArray.size(); i++) {
String[] sArray = inventoryArray.get(i);
String sku = sArray[1];
try {
theKey = new DatabaseEntry(sku.getBytes("UTF-8"));
} catch (IOException willNeverOccur) {}
Inventory theInventory = new Inventory();
theInventory.setItemName(sArray[0]);
theInventory.setSku(sArray[1]);
theInventory.setVendorPrice(
(new Float(sArray[2])).floatValue());
theInventory.setVendorInventory(
(new Integer(sArray[3])).intValue());
theInventory.setCategory(sArray[4]);
theInventory.setVendor(sArray[5]);
// Place the Vendor object on the DatabaseEntry object using
// our the tuple binding we implemented in
// InventoryBinding.java
inventoryBinding.objectToEntry(theInventory, theData);
// Put it in the database.
myDbEnv.getInventoryDB().put(null, theKey, theData);
}
}</pre>
<p>The remainder of this application provides utility methods to
read a flat text file into an array of strings and parse the
command line options. From the perspective of this document, these
things are relatively uninteresting. You can see how they are
implemented by looking at:
</p>
<pre class="programlisting"><span class="emphasis"><em>JE_HOME</em></span>/examples/je/gettingStarted/ExampleDataPut.java </pre>
<p>
where <code class="literal"><span class="emphasis"><em>JE_HOME</em></span></code> is the location where you
placed your JE distribution.
</p>
<a id="je_dbt30"></a>
<pre class="programlisting"> private static void parseArgs(String args[]) {
// Implementation omitted for brevity.
}
private List loadFile(File theFile, int numFields) {
List&lt;String[]&gt; records = new ArrayList&lt;String[]&gt;();
// Implementation omitted for brevity.
return records;
}
protected ExampleDatabasePut() {}
} </pre>
</div>
</div>
<br class="example-break" />
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="comparator.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="DBEntry.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="Cursors.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Using Comparators </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Chapter 9. Using Cursors</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,124 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Setting Disk Thresholds</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="administration.html" title="Chapter 12. Administering Berkeley DB Java Edition Applications" />
<link rel="prev" href="cachesize.html" title="Sizing the Cache" />
<link rel="next" href="commandlinetools.html" title="The Command Line Tools" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Setting Disk Thresholds</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="cachesize.html">Prev</a> </td>
<th width="60%" align="center">Chapter 12. Administering Berkeley DB Java Edition Applications</th>
<td width="20%" align="right"> <a accesskey="n" href="commandlinetools.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="diskthreshold"></a>Setting Disk Thresholds</h2>
</div>
</div>
</div>
<p>
You can control the maximum amount of disk space that JE can use by setting two different
threshold values. If JE exceeds either of these threshold values, writes will no longer
be allowed to the database. Instead, when a write is attempted, <a class="ulink" href="../java/com/sleepycat/je/DiskLimitException.html" target="_top">DiskLimitException</a> is thrown.
The thresholds you can set are:
</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>
<a class="ulink" href="../java/com/sleepycat/je/EnvironmentConfig.html#MAX_DISK" target="_top">EnvironmentConfig.MAX_DISK</a>
</p>
<p>
Specifies an upper limit on the total number of bytes that can be used for data storage.
By default, this property is set to <code class="literal">0</code>, which means no upper
limit is enforced. Instead, the value set for <a class="ulink" href="../java/com/sleepycat/je/EnvironmentConfig.html#FREE_DISK" target="_top">EnvironmentConfig.FREE_DISK</a> will control your
how much disk space your database is allowed to consume.
</p>
<p>
If multiple JE environments share the same storage volume, Oracle recommends that you
set <a class="ulink" href="../java/com/sleepycat/je/EnvironmentConfig.html#MAX_DISK" target="_top">EnvironmentConfig.MAX_DISK</a> to a non-zero value, especially if an external application or service is
also consuming space on the disk volume.
</p>
<p>
This value can be managed using the <a class="ulink" href="../java/com/sleepycat/je/EnvironmentMutableConfig.html#setMaxDisk-long-" target="_top">EnvironmentMutableConfig.setMaxDisk()</a> method.
</p>
</li>
<li>
<p>
<a class="ulink" href="../java/com/sleepycat/je/EnvironmentConfig.html#FREE_DISK" target="_top">EnvironmentConfig.FREE_DISK</a>
</p>
<p>
Specifies the minimum amount of free space to maintain on the disk volume. The
default value is 5 GB, which is large enough to allow manual recovery if the
free space threshold is exceeded.
</p>
<p>
If <a class="ulink" href="../java/com/sleepycat/je/EnvironmentConfig.html#MAX_DISK" target="_top">EnvironmentConfig.MAX_DISK</a> is set to <code class="literal">0</code>, then the total amount of
space your JE database can consume is:
</p>
<pre class="programlisting">&lt;disk_size&gt; - &lt;FREE_DISK&gt;</pre>
<p>
So for a 300 GB volume and a free disk size of 5 GB, your database can grow
to consume 295 GB.
</p>
<p>
If <a class="ulink" href="../java/com/sleepycat/je/EnvironmentConfig.html#MAX_DISK" target="_top">EnvironmentConfig.MAX_DISK</a> is set to a non-zero value, then the total amount of space
your JE database can consume is:
</p>
<pre class="programlisting">&lt;MAX_DISK&gt; - &lt;FREE_DISK&gt;</pre>
<p>
So for the same 300 GB volume, if max disk is 100 GB and free disk is 5 GB, then
your database can consume at most 95 GB.
</p>
<p>
Be aware that the subtraction shown, above, is performed only if <a class="ulink" href="../java/com/sleepycat/je/EnvironmentConfig.html#FREE_DISK" target="_top">EnvironmentConfig.FREE_DISK</a> is explicitly
set or <a class="ulink" href="../java/com/sleepycat/je/EnvironmentConfig.html#MAX_DISK" target="_top">EnvironmentConfig.MAX_DISK</a> is greater than 10GB. See the <a class="ulink" href="../java/com/sleepycat/je/EnvironmentConfig.html#FREE_DISK" target="_top">EnvironmentConfig.FREE_DISK</a> Javadoc for more information.
</p>
</li>
</ul>
</div>
<p>
For usage scenarios, see the <a class="ulink" href="../java/com/sleepycat/je/EnvironmentConfig.html#MAX_DISK" target="_top">EnvironmentConfig.MAX_DISK</a> Javadoc.
</p>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="cachesize.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="administration.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="commandlinetools.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Sizing the Cache </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> The Command Line Tools</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,279 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Part I. Programming with the Direct Persistence Layer</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="prev" href="dbenvUsageExample.html" title="Database Environment Management Example" />
<link rel="next" href="persist_first.html" title="Chapter 3. Direct Persistence Layer First Steps" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Part I. Programming with the Direct Persistence Layer</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="dbenvUsageExample.html">Prev</a> </td>
<th width="60%" align="center"> </th>
<td width="20%" align="right"> <a accesskey="n" href="persist_first.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="part" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h1 class="title"><a id="dpl"></a>Part I. Programming with the Direct Persistence Layer</h1>
</div>
</div>
</div>
<div class="partintro" lang="en" xml:lang="en">
<div></div>
<p>
This section discusses how to build an
application using the DPL. The DPL is ideally
suited for those applications that want a
mechanism for storing and managing Java class
objects in a JE database. Note that the DPL
is best suited for applications that work with
classes with a relatively static schema.
</p>
<p>
The DPL requires Java 1.5.
</p>
<p>
If you are porting an application
from the Berkeley DB API, then you probably want
to use the base API instead of the DPL. For
information on using the base API, see
<a class="xref" href="baseapi.html" title="Part II. Programming with the Base API">Programming with the Base API</a>.
</p>
<div class="toc">
<p>
<b>Table of Contents</b>
</p>
<dl>
<dt>
<span class="chapter">
<a href="persist_first.html">3. Direct Persistence Layer First Steps</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect1">
<a href="persist_first.html#entitystore">Entity Stores</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect2">
<a href="persist_first.html#persist-open">Opening and Closing Environments and Stores</a>
</span>
</dt>
</dl>
</dd>
<dt>
<span class="sect1">
<a href="persistobject.html">Persistent Objects</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="saveret.html">Saving and Retrieving Data</a>
</span>
</dt>
</dl>
</dd>
<dt>
<span class="chapter">
<a href="persist_index.html">4. Working with Indices</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect1">
<a href="persist_index.html#dplindexaccess">Accessing Indexes</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect2">
<a href="persist_index.html#primaryindexaccess">Accessing Primary Indices</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="persist_index.html#secondaryindexaccess">Accessing Secondary Indices</a>
</span>
</dt>
</dl>
</dd>
<dt>
<span class="sect1">
<a href="dplindexcreate.html">Creating Indexes</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect2">
<a href="dplindexcreate.html#dplprimaryidxdecl">Declaring Primary Indexes</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="dplindexcreate.html#dplsecondaryidxdecl">Declaring Secondary Indexes</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="dplindexcreate.html#foreignkey">Foreign Key Constraints</a>
</span>
</dt>
</dl>
</dd>
</dl>
</dd>
<dt>
<span class="chapter">
<a href="persist_access.html">5. Saving and Retrieving Objects</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect1">
<a href="persist_access.html#simpleentity">A Simple Entity Class</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="simpleda.html">SimpleDA.class</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="simpleput.html">Placing Objects in an Entity Store</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="simpleget.html">Retrieving Objects from an Entity Store</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="getmultiple.html">Retrieving Multiple Objects</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect2">
<a href="getmultiple.html#dpl_cursor_initialize">Cursor Initialization</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="getmultiple.html#dpl_dups">Working with Duplicate Keys</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="getmultiple.html#dpl_cursor_range">Key Ranges</a>
</span>
</dt>
</dl>
</dd>
<dt>
<span class="sect1">
<a href="dpl_entityjoin.html">Join Cursors</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="dpl_delete.html">Deleting Entity Objects</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="dpl_replace.html">Replacing Entity Objects</a>
</span>
</dt>
</dl>
</dd>
<dt>
<span class="chapter">
<a href="dpl_example.html">6. A DPL Example</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect1">
<a href="dpl_example.html#vendorclass">Vendor.java</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="inventoryclass.html">Inventory.java</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="mydbenv-persist.html">MyDbEnv</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="dataaccessorclass.html">DataAccessor.java</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="dpl_exampledatabaseput.html">ExampleDatabasePut.java</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="dpl_exampleinventoryread.html">ExampleInventoryRead.java</a>
</span>
</dt>
</dl>
</dd>
</dl>
</div>
</div>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="dbenvUsageExample.html">Prev</a> </td>
<td width="20%" align="center"> </td>
<td width="40%" align="right"> <a accesskey="n" href="persist_first.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Database Environment Management Example </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Chapter 3. Direct Persistence Layer First Steps</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,114 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Deleting Entity Objects</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="persist_access.html" title="Chapter 5. Saving and Retrieving Objects" />
<link rel="prev" href="dpl_entityjoin.html" title="Join Cursors" />
<link rel="next" href="dpl_replace.html" title="Replacing Entity Objects" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Deleting Entity Objects</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="dpl_entityjoin.html">Prev</a> </td>
<th width="60%" align="center">Chapter 5. Saving and Retrieving Objects</th>
<td width="20%" align="right"> <a accesskey="n" href="dpl_replace.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="dpl_delete"></a>Deleting Entity Objects</h2>
</div>
</div>
</div>
<p>
The simplest way to remove an object from your entity store
is to delete it by its primary index. For example,
using the <code class="classname">SimpleDA</code> class that we
created earlier in this document
(see <a class="xref" href="simpleda.html" title="SimpleDA.class">SimpleDA.class</a>),
you can delete the <code class="classname">SimpleEntityClass</code>
object with a primary key of <code class="literal">keyone</code> as
follows:
</p>
<pre class="programlisting">sda.pIdx.delete("keyone");</pre>
<p>
You can also delete objects by their secondary keys. When
you do this, all objects related to the secondary key are
deleted, unless the key is a foreign object.
</p>
<p>
For example, the following deletes all
<code class="classname">SimpleEntityClass</code> with a secondary
key of <code class="literal">skeyone</code>:
</p>
<pre class="programlisting">sda.sIdx.delete("skeyone");</pre>
<p>
You can delete any single object by positioning a cursor to
that object and then calling the cursor's
<code class="methodname">delete()</code> method.
</p>
<pre class="programlisting">PrimaryIndex&lt;String,SimpleEntityClass&gt; pi =
store.getPrimaryIndex(String.class, SimpleEntityClass.class);
SecondaryIndex&lt;String,String,SimpleEntityClass&gt; si =
store.getSecondaryIndex(pi, String.class, "sKey");
EntityCursor&lt;SimpleEntityClass&gt; sec_cursor =
si.subIndex("skeyone").entities();
try {
SimpleEntityClass sec;
Iterator&lt;SimpleEntityClass&gt; i = sec_cursor.iterator();
while (sec = i.nextDup() != null) {
if (sec.getSKey() == "some value") {
i.delete();
}
}
// Always make sure the cursor is closed when we are done with it.
} finally {
sec_cursor.close(); } </pre>
<p>
Finally, if you are indexing by foreign key, then the
results of deleting the key is determined by the foreign
key constraint that you have set for the index. See
<a class="xref" href="dplindexcreate.html#foreignkey" title="Foreign Key Constraints">Foreign Key Constraints</a>
for more information.
</p>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="dpl_entityjoin.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="persist_access.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="dpl_replace.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Join Cursors </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Replacing Entity Objects</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,193 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Join Cursors</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="persist_access.html" title="Chapter 5. Saving and Retrieving Objects" />
<link rel="prev" href="getmultiple.html" title="Retrieving Multiple Objects" />
<link rel="next" href="dpl_delete.html" title="Deleting Entity Objects" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Join Cursors</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="getmultiple.html">Prev</a> </td>
<th width="60%" align="center">Chapter 5. Saving and Retrieving Objects</th>
<td width="20%" align="right"> <a accesskey="n" href="dpl_delete.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="dpl_entityjoin"></a>Join Cursors</h2>
</div>
</div>
</div>
<p>
If you have two or more secondary indexes set for
an entity object, then you can retrieve sets of
objects based on the intersection of multiple
secondary index values. You do this using an
<code class="classname">EntityJoin</code>
class.
</p>
<p>
For example, suppose you had an entity class that
represented automobiles. In that case, you might
be storing information about automobiles such as
color, number of doors, fuel mileage,
automobile type, number of passengers, make, model, and year,
to name just a few.
</p>
<p>
If you created a secondary index based this
information, then you could use an
<code class="classname">EntityJoin</code> to return
all those objects representing cars with, say, two
doors, that were built in 2002, and which are green
in color.
</p>
<p>
To create a join cursor, you:
</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>
Open the primary index for the
entity class on which you want to
perform the join.
</p>
</li>
<li>
<p>
Open the secondary indexes that you
want to use for the join.
</p>
</li>
<li>
<p>
Instantiate an
<code class="classname">EntityJoin</code>
object (you use the primary index
to do this).
</p>
</li>
<li>
<p>
Use two or more calls to
<code class="methodname">EntityJoin.addCondition()</code>
to identify the secondary indexes
and their values that you want to use
for the equality match.
</p>
</li>
<li>
<p>
Call
<code class="methodname">EntityJoin.entities()</code>
to obtain a cursor that you can use
to iterate over the join results.
</p>
</li>
</ol>
</div>
<p>
For example, suppose we had an entity class
that included the following features:
</p>
<pre class="programlisting">package persist.gettingStarted;
import com.sleepycat.persist.model.Entity;
import com.sleepycat.persist.model.PrimaryKey;
import static com.sleepycat.persist.model.Relationship.*;
import com.sleepycat.persist.model.SecondaryKey;
@Entity
public class Automobiles {
// Primary key is the vehicle identification number
@PrimaryKey
private String vin;
// Secondary key is the vehicle's make
@SecondaryKey(relate=MANY_TO_ONE)
private String make;
// Secondary key is the vehicle's color
@SecondaryKey(relate=MANY_TO_ONE)
private String color;
...
public String getVIN() {
return vin;
}
public String getMake() {
return make;
}
public String getColor() {
return color;
}
... </pre>
<p>
Then we could perform an entity join that searches for all the
red automobiles made by Toyota as follows:
</p>
<pre class="programlisting">
PrimaryIndex&lt;String,Automobiles&gt; vin_pidx;
SecondaryIndex&lt;String,String,Automobiles&gt; make_sidx;
SecondaryIndex&lt;String,String,Automobiles&gt; color_sidx;
EntityJoin&lt;String,Automobiles&gt; join = new EntityJoin(vin_pidx);
join.addCondition(make_sidx,"Toyota");
join.addCondition(color_sidx,"Red");
// Now iterate over the results of the join operation
ForwardCursor&lt;Automobiles&gt; join_cursor = join.entities();
try {
for (Automobiles autoi : join_cursor) {
// do something with each object "autoi"
}
// Always make sure the cursor is closed when we are done with it.
} finally {
join_cursor.close();
} </pre>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="getmultiple.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="persist_access.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="dpl_delete.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Retrieving Multiple Objects </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Deleting Entity Objects</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,275 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Chapter 6. A DPL Example</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="dpl.html" title="Part I. Programming with the Direct Persistence Layer" />
<link rel="prev" href="dpl_replace.html" title="Replacing Entity Objects" />
<link rel="next" href="inventoryclass.html" title="Inventory.java" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Chapter 6. A DPL Example</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="dpl_replace.html">Prev</a> </td>
<th width="60%" align="center">Part I. Programming with the Direct Persistence Layer</th>
<td width="20%" align="right"> <a accesskey="n" href="inventoryclass.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="chapter" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title"><a id="dpl_example"></a>Chapter 6. A DPL Example</h2>
</div>
</div>
</div>
<div class="toc">
<p>
<b>Table of Contents</b>
</p>
<dl>
<dt>
<span class="sect1">
<a href="dpl_example.html#vendorclass">Vendor.java</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="inventoryclass.html">Inventory.java</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="mydbenv-persist.html">MyDbEnv</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="dataaccessorclass.html">DataAccessor.java</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="dpl_exampledatabaseput.html">ExampleDatabasePut.java</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="dpl_exampleinventoryread.html">ExampleInventoryRead.java</a>
</span>
</dt>
</dl>
</div>
<p>
In order to illustrate DPL usage, we provide a
complete working example in this chapter. This example
reads and writes inventory and vendor information for a
mythical business. The application consists of the
following classes:
</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>
Several classes used to encapsulate our
application's data. See
<a class="xref" href="dpl_example.html#vendorclass" title="Vendor.java">Vendor.java</a>
and
<a class="xref" href="inventoryclass.html" title="Inventory.java">Inventory.java</a>.
</p>
</li>
<li>
<p>
A convenience class used to open and close
our environment and entity store. See
<a class="xref" href="mydbenv-persist.html" title="MyDbEnv">MyDbEnv</a>.
</p>
</li>
<li>
<p>
A class that loads data into the store. See
<a class="xref" href="dpl_exampledatabaseput.html" title="ExampleDatabasePut.java">ExampleDatabasePut.java</a>.
</p>
</li>
<li>
<p>
Finally, a class that reads data from the
store. See
<a class="xref" href="dpl_exampleinventoryread.html" title="ExampleInventoryRead.java">ExampleInventoryRead.java</a>.
</p>
</li>
</ul>
</div>
<p>
Be aware that this example can be found in your JE distribution in
the following location:
</p>
<p>
<span class="emphasis"><em>JE_HOME</em></span>/examples/persist/gettingStarted
</p>
<p>
where <code class="literal"><span class="emphasis"><em>JE_HOME</em></span></code> is the location where you
placed your JE distribution.
</p>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="vendorclass"></a>Vendor.java</h2>
</div>
</div>
</div>
<p>
The simplest class that our example wants to store contains
vendor contact information. This class contains no
secondary indices so all we have to do is identify it
as an entity class and identify the field in the
class used for the primary key.
</p>
<p>
In the following example, we identify the
<code class="literal">vendor</code> data member as containing the
primary key. This data member is meant to contain a
vendor's name. Because of the way we will use our
<code class="classname">EntityStore</code>, the value
provided for this data member must be unique within
the store or runtime errors will result.
</p>
<p>
When used with the DPL, our
<code class="classname">Vendor</code> class appears as
follows. Notice that the <code class="literal">@Entity</code>
annotation appears immediately before the class
declaration, and the <code class="literal">@PrimaryKey</code>
annotation appears immediately before the
<code class="literal">vendor</code> data member declaration.
</p>
<pre class="programlisting">package persist.gettingStarted;
import com.sleepycat.persist.model.Entity;
import com.sleepycat.persist.model.PrimaryKey;
@Entity
public class Vendor {
private String address;
private String bizPhoneNumber;
private String city;
private String repName;
private String repPhoneNumber;
private String state;
// Primary key is the vendor's name
// This assumes that the vendor's name is
// unique in the database.
@PrimaryKey
private String vendor;
private String zipcode;
public void setRepName(String data) {
repName = data;
}
public void setAddress(String data) {
address = data;
}
public void setCity(String data) {
city = data;
}
public void setState(String data) {
state = data;
}
public void setZipcode(String data) {
zipcode = data;
}
public void setBusinessPhoneNumber(String data) {
bizPhoneNumber = data;
}
public void setRepPhoneNumber(String data) {
repPhoneNumber = data;
}
public void setVendorName(String data) {
vendor = data;
}
public String getRepName() {
return repName;
}
public String getAddress() {
return address;
}
public String getCity() {
return city;
}
public String getState() {
return state;
}
public String getZipcode() {
return zipcode;
}
public String getBusinessPhoneNumber() {
return bizPhoneNumber;
}
public String getRepPhoneNumber() {
return repPhoneNumber;
}
} </pre>
<p>
For this class, the <code class="literal">vendor</code> value is set for an individual
<code class="classname">Vendor</code> class object by
the <code class="methodname">setVendorName()</code>
method. If our example code fails to set this
value before storing the object, the data
member used to store the primary key is set to a
null value. This would result in a runtime
error.
</p>
</div>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="dpl_replace.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="dpl.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="inventoryclass.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Replacing Entity Objects </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Inventory.java</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,337 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>ExampleDatabasePut.java</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="dpl_example.html" title="Chapter 6. A DPL Example" />
<link rel="prev" href="dataaccessorclass.html" title="DataAccessor.java" />
<link rel="next" href="dpl_exampleinventoryread.html" title="ExampleInventoryRead.java" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">ExampleDatabasePut.java</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="dataaccessorclass.html">Prev</a> </td>
<th width="60%" align="center">Chapter 6. A DPL Example</th>
<td width="20%" align="right"> <a accesskey="n" href="dpl_exampleinventoryread.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="dpl_exampledatabaseput"></a>ExampleDatabasePut.java</h2>
</div>
</div>
</div>
<p>
Our example reads inventory and vendor information from
flat text files, encapsulates this data in objects of
the appropriate type, and then writes each object to an
<code class="classname">EntityStore</code>.
</p>
<p>
To begin, we import the Java classes that our example
needs. Most of the imports are related to reading the raw
data from flat text files and breaking them apart for usage
with our data classes. We also import classes from the
JE package, but we do not actually import any classes
from the DPL. The reason why is because we have
placed almost all of our DPL work off into
other classes, so there is no need for direct usage of
those APIs here.
</p>
<pre class="programlisting">package persist.gettingStarted;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import com.sleepycat.je.DatabaseException; </pre>
<p>
Now we can begin the class itself. Here we set default paths
for the on-disk resources that we require (the environment
home, and the location of the text files containing our sample
data). We also declare <code class="classname">DataAccessor</code>
and <code class="classname">MyDbEnv</code> members. We describe these
classes and show their implementation in
<a class="xref" href="dataaccessorclass.html" title="DataAccessor.java">DataAccessor.java</a>
and
<a class="xref" href="mydbenv-persist.html" title="MyDbEnv">MyDbEnv</a>.
</p>
<pre class="programlisting">public class ExampleDatabasePut {
private static File myDbEnvPath = new File("/tmp/JEDB");
private static File inventoryFile = new File("./inventory.txt");
private static File vendorsFile = new File("./vendors.txt");
private DataAccessor da;
// Encapsulates the environment and data store.
private static MyDbEnv myDbEnv = new MyDbEnv();</pre>
<p>
Next, we provide our <code class="methodname">usage()</code>
method. The command line options provided there are necessary
only if the default values to the on-disk resources are not
sufficient.
</p>
<pre class="programlisting"> private static void usage() {
System.out.println("ExampleDatabasePut [-h &lt;env directory&gt;]");
System.out.println(" [-i &lt;inventory file&gt;]");
System.out.println(" [-v &lt;vendors file&gt;]");
System.exit(-1);
} </pre>
<p>
Our <code class="methodname">main()</code> method is also reasonably
self-explanatory. We simply instantiate an
<code class="classname">ExampleDatabasePut</code> object there and then
call its <code class="methodname">run()</code> method. We also provide a
top-level <code class="literal">try</code> block there for any exceptions that might be thrown
during runtime.
</p>
<p>
Notice that the <code class="literal">finally</code> statement in the
top-level <code class="literal">try</code> block calls
<code class="methodname">MyDbEnv.close()</code>. This method closes our
<code class="classname">EntityStore</code> and <code class="classname">Environment</code>
objects. By placing it here in the <code class="literal">finally</code>
statement, we can make sure that our store and environment are
always cleanly closed.
</p>
<pre class="programlisting"> public static void main(String args[]) {
ExampleDatabasePut edp = new ExampleDatabasePut();
try {
edp.run(args);
} catch (DatabaseException dbe) {
System.err.println("ExampleDatabasePut: " + dbe.toString());
dbe.printStackTrace();
} catch (Exception e) {
System.out.println("Exception: " + e.toString());
e.printStackTrace();
} finally {
myDbEnv.close();
}
System.out.println("All done.");
} </pre>
<p>
Our <code class="methodname">run()</code> method does four
things. It calls <code class="methodname">MyDbEnv.setup()</code>,
which opens our <code class="classname">Environment</code> and
<code class="classname">EntityStore</code>. It then instantiates a
<code class="classname">DataAccessor</code> object, which we will use
to write data to the store. It calls
<code class="methodname">loadVendorsDb()</code> which loads all of the
vendor information. And then it calls
<code class="methodname">loadInventoryDb()</code> which loads all of
the inventory information.
</p>
<p>
Notice that the <code class="classname">MyDbEnv</code>
object is being setup as read-write. This results in the
<code class="classname">EntityStore</code> being opened for
transactional support.
(See <a class="xref" href="mydbenv-persist.html" title="MyDbEnv">MyDbEnv</a>
for implementation details.)
</p>
<pre class="programlisting"> private void run(String args[])
throws DatabaseException {
// Parse the arguments list
parseArgs(args);
myDbEnv.setup(myDbEnvPath, // Path to the environment home
false); // Environment read-only?
// Open the data accessor. This is used to store
// persistent objects.
da = new DataAccessor(myDbEnv.getEntityStore());
System.out.println("loading vendors db....");
loadVendorsDb();
System.out.println("loading inventory db....");
loadInventoryDb();
} </pre>
<p>
We can now implement the <code class="methodname">loadVendorsDb()</code>
method. This method is responsible for reading the vendor
contact information from the appropriate flat-text file,
populating <code class="classname">Vendor</code> class objects with the
data and then writing it to the <code class="classname">EntityStore</code>.
As explained above, each individual object is written with
transactional support. However, because a transaction handle is
not explicitly used, the write is performed using auto-commit.
This happens because the <code class="classname">EntityStore</code>
was opened to support transactions.
</p>
<p>
To actually write each class to the
<code class="classname">EntityStore</code>, we simply call the
<code class="methodname">PrimaryIndex.put()</code> method for the
<code class="classname">Vendor</code> entity instance. We obtain this
method from our <code class="classname">DataAccessor</code>
class.
</p>
<pre class="programlisting"> private void loadVendorsDb()
throws DatabaseException {
// loadFile opens a flat-text file that contains our data
// and loads it into a list for us to work with. The integer
// parameter represents the number of fields expected in the
// file.
List vendors = loadFile(vendorsFile, 8);
// Now load the data into the store.
for (int i = 0; i &lt; vendors.size(); i++) {
String[] sArray = (String[])vendors.get(i);
Vendor theVendor = new Vendor();
theVendor.setVendorName(sArray[0]);
theVendor.setAddress(sArray[1]);
theVendor.setCity(sArray[2]);
theVendor.setState(sArray[3]);
theVendor.setZipcode(sArray[4]);
theVendor.setBusinessPhoneNumber(sArray[5]);
theVendor.setRepName(sArray[6]);
theVendor.setRepPhoneNumber(sArray[7]);
// Put it in the store.
da.vendorByName.put(theVendor);
}
} </pre>
<p>
Now we can implement our <code class="methodname">loadInventoryDb()</code>
method. This does exactly the same thing as the
<code class="methodname">loadVendorsDb()</code>
method.
</p>
<pre class="programlisting"> private void loadInventoryDb()
throws DatabaseException {
// loadFile opens a flat-text file that contains our data
// and loads it into a list for us to work with. The integer
// parameter represents the number of fields expected in the
// file.
List inventoryArray = loadFile(inventoryFile, 6);
// Now load the data into the store. The item's sku is the
// key, and the data is an Inventory class object.
for (int i = 0; i &lt; inventoryArray.size(); i++) {
String[] sArray = (String[])inventoryArray.get(i);
String sku = sArray[1];
Inventory theInventory = new Inventory();
theInventory.setItemName(sArray[0]);
theInventory.setSku(sArray[1]);
theInventory.setVendorPrice(
(new Float(sArray[2])).floatValue());
theInventory.setVendorInventory(
(new Integer(sArray[3])).intValue());
theInventory.setCategory(sArray[4]);
theInventory.setVendor(sArray[5]);
// Put it in the store. Note that this causes our secondary key
// to be automatically updated for us.
da.inventoryBySku.put(theInventory);
}
} </pre>
<p>
The remainder of this example simple parses the command line
and loads data from a flat-text file. There is nothing here
that is of specific interest to the DPL, but we
show this part of the example anyway in the interest of
completeness.
</p>
<pre class="programlisting"> private static void parseArgs(String args[]) {
for(int i = 0; i &lt; args.length; ++i) {
if (args[i].startsWith("-")) {
switch(args[i].charAt(1)) {
case 'h':
myDbEnvPath = new File(args[++i]);
break;
case 'i':
inventoryFile = new File(args[++i]);
break;
case 'v':
vendorsFile = new File(args[++i]);
break;
default:
usage();
}
}
}
}
private List loadFile(File theFile, int numFields) {
List&lt;String[]&gt; records = new ArrayList&lt;String[]&gt;();
try {
String theLine = null;
FileInputStream fis = new FileInputStream(theFile);
BufferedReader br =
new BufferedReader(new InputStreamReader(fis));
while((theLine=br.readLine()) != null) {
String[] theLineArray = theLine.split("#");
if (theLineArray.length != numFields) {
System.out.println("Malformed line found in " +
theFile.getPath());
System.out.println("Line was: '" + theLine);
System.out.println("length found was: " +
theLineArray.length);
System.exit(-1);
}
records.add(theLineArray);
}
// Close the input stream handle
fis.close();
} catch (FileNotFoundException e) {
System.err.println(theFile.getPath() + " does not exist.");
e.printStackTrace();
usage();
} catch (IOException e) {
System.err.println("IO Exception: " + e.toString());
e.printStackTrace();
System.exit(-1);
}
return records;
}
protected ExampleDatabasePut() {}
} </pre>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="dataaccessorclass.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="dpl_example.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="dpl_exampleinventoryread.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">DataAccessor.java </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> ExampleInventoryRead.java</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,271 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>ExampleInventoryRead.java</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="dpl_example.html" title="Chapter 6. A DPL Example" />
<link rel="prev" href="dpl_exampledatabaseput.html" title="ExampleDatabasePut.java" />
<link rel="next" href="baseapi.html" title="Part II. Programming with the Base API" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">ExampleInventoryRead.java</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="dpl_exampledatabaseput.html">Prev</a> </td>
<th width="60%" align="center">Chapter 6. A DPL Example</th>
<td width="20%" align="right"> <a accesskey="n" href="baseapi.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="dpl_exampleinventoryread"></a>ExampleInventoryRead.java</h2>
</div>
</div>
</div>
<p>
<code class="classname">ExampleInventoryRead</code>
retrieves
inventory information from our entity store and
displays it. When it displays each inventory item, it
also displays the related vendor contact information.
</p>
<p>
<code class="classname">ExampleInventoryRead</code>
can do one of two things. If you provide no search
criteria, it displays all of the inventory items in the
store. If you provide an item name (using the
<code class="literal">-s</code> command line switch), then just
those inventory items using that name are displayed.
</p>
<p>
The beginning of our example is almost identical to our
<code class="classname">ExampleDatabasePut</code>
example program. We
repeat that example code here for the sake of
completeness. For a complete walk-through of it, see
the previous section (<a class="xref" href="dpl_exampledatabaseput.html" title="ExampleDatabasePut.java">ExampleDatabasePut.java</a>).
</p>
<pre class="programlisting">package persist.gettingStarted;
import java.io.File;
import java.io.IOException;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.persist.EntityCursor;
public class ExampleInventoryRead {
private static File myDbEnvPath =
new File("/tmp/JEDB");
private DataAccessor da;
// Encapsulates the database environment.
private static MyDbEnv myDbEnv = new MyDbEnv();
// The item to locate if the -s switch is used
private static String locateItem;
private static void usage() {
System.out.println("ExampleInventoryRead [-h &lt;env directory&gt;]" +
"[-s &lt;item to locate&gt;]");
System.exit(-1);
}
public static void main(String args[]) {
ExampleInventoryRead eir = new ExampleInventoryRead();
try {
eir.run(args);
} catch (DatabaseException dbe) {
System.err.println("ExampleInventoryRead: " + dbe.toString());
dbe.printStackTrace();
} finally {
myDbEnv.close();
}
System.out.println("All done.");
}
private void run(String args[])
throws DatabaseException {
// Parse the arguments list
parseArgs(args);
myDbEnv.setup(myDbEnvPath, // path to the environment home
true); // is this environment read-only?
// Open the data accessor. This is used to retrieve
// persistent objects.
da = new DataAccessor(myDbEnv.getEntityStore());
// If a item to locate is provided on the command line,
// show just the inventory items using the provided name.
// Otherwise, show everything in the inventory.
if (locateItem != null) {
showItem();
} else {
showAllInventory();
}
} </pre>
<p>
The first method that we provide is used to show inventory
items related to a given inventory name. This method is called
only if an inventory name is passed to
<code class="classname">ExampleInventoryRead</code>
via the <code class="literal">-s</code> option. Given the sample data
that we provide with this example, each matching inventory name
will result in the display of three inventory objects.
</p>
<p>
To display these objects we use the
<code class="classname">Inventory</code> class'
<code class="literal">inventoryByName</code> secondary index to retrieve
an <code class="classname">EntityCursor</code>, and then we iterate
over the resulting objects using the cursor.
</p>
<p>
Notice that this method calls
<code class="methodname">displayInventoryRecord()</code>
to display each individual object. We show this
method a little later in the example.
</p>
<pre class="programlisting"> // Shows all the inventory items that exist for a given
// inventory name.
private void showItem() throws DatabaseException {
// Use the inventory name secondary key to retrieve
// these objects.
EntityCursor&lt;Inventory&gt; items =
da.inventoryByName.subIndex(locateItem).entities();
try {
for (Inventory item : items) {
displayInventoryRecord(item);
}
} finally {
items.close();
}
} </pre>
<p>
Next we implement <code class="methodname">showAllInventory()</code>,
which shows all of the <code class="classname">Inventory</code>
objects in the store. To do this, we
obtain an <code class="classname">EntityCursor</code>
from the <code class="classname">Inventory</code> class'
primary index and, again, we iterate using that cursor.
</p>
<pre class="programlisting"> // Displays all the inventory items in the store
private void showAllInventory()
throws DatabaseException {
// Get a cursor that will walk every
// inventory object in the store.
EntityCursor&lt;Inventory&gt; items =
da.inventoryBySku.entities();
try {
for (Inventory item : items) {
displayInventoryRecord(item);
}
} finally {
items.close();
}
} </pre>
<p>
Now we implement
<code class="methodname">displayInventoryRecord()</code>. This
uses the getter methods on the <code class="classname">Inventory</code>
class to obtain the information that we want to display.
The only thing interesting about this method is that we
obtain <code class="classname">Vendor</code> objects within.
The vendor objects are retrieved <code class="classname">Vendor</code>
objects using their primary index. We get the key
for the retrieval from the <code class="classname">Inventory</code>
object that we are displaying at the time.
</p>
<pre class="programlisting"> private void displayInventoryRecord(Inventory theInventory)
throws DatabaseException {
System.out.println(theInventory.getSku() + ":");
System.out.println("\t " + theInventory.getItemName());
System.out.println("\t " + theInventory.getCategory());
System.out.println("\t " + theInventory.getVendor());
System.out.println("\t\tNumber in stock: " +
theInventory.getVendorInventory());
System.out.println("\t\tPrice per unit: " +
theInventory.getVendorPrice());
System.out.println("\t\tContact: ");
Vendor theVendor =
da.vendorByName.get(theInventory.getVendor());
assert theVendor != null;
System.out.println("\t\t " + theVendor.getAddress());
System.out.println("\t\t " + theVendor.getCity() + ", " +
theVendor.getState() + " " + theVendor.getZipcode());
System.out.println("\t\t Business Phone: " +
theVendor.getBusinessPhoneNumber());
System.out.println("\t\t Sales Rep: " +
theVendor.getRepName());
System.out.println("\t\t " +
theVendor.getRepPhoneNumber());
} </pre>
<p>
The last remaining parts of the example are used to parse
the command line. This is not very
interesting for our purposes here, but we show it anyway
for the sake of completeness.
</p>
<pre class="programlisting"> protected ExampleInventoryRead() {}
private static void parseArgs(String args[]) {
for(int i = 0; i &lt; args.length; ++i) {
if (args[i].startsWith("-")) {
switch(args[i].charAt(1)) {
case 'h':
myDbEnvPath = new File(args[++i]);
break;
case 's':
locateItem = args[++i];
break;
default:
usage();
}
}
}
}
} </pre>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="dpl_exampledatabaseput.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="dpl_example.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="baseapi.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">ExampleDatabasePut.java </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Part II. Programming with the Base API</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,109 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Replacing Entity Objects</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="persist_access.html" title="Chapter 5. Saving and Retrieving Objects" />
<link rel="prev" href="dpl_delete.html" title="Deleting Entity Objects" />
<link rel="next" href="dpl_example.html" title="Chapter 6. A DPL Example" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Replacing Entity Objects</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="dpl_delete.html">Prev</a> </td>
<th width="60%" align="center">Chapter 5. Saving and Retrieving Objects</th>
<td width="20%" align="right"> <a accesskey="n" href="dpl_example.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="dpl_replace"></a>Replacing Entity Objects</h2>
</div>
</div>
</div>
<p>
To modify a stored entity object, retrieve it, update
it, then put it back to the entity store:
</p>
<pre class="programlisting">
SimpleEntityClass sec = sda.pIdx.get("keyone");
sec.setSKey("skeyoneupdated");
sda.pIdx.put(sec);
</pre>
<p>
Note that because we updated a field on the object that is
a secondary key, this object will now be accessible by the
secondary key of <code class="literal">skeyoneupdated</code> instead
of the previous value, which was <code class="literal">skeyone</code>
</p>
<p>
Be aware that if you modify the object's primary key, the behavior is
somewhat different. In this case, you cause a new instance
of the object to be created in the store, instead of
replacing an existing instance:
</p>
<pre class="programlisting">// Results in two objects in the store. One with a
// primary index of "keyfive" and the other with primary index of
//'keyfivenew'.
SimpleEntityClass sec = sda.pIdx.get("keyfive");
sec.setPKey("keyfivenew");
sda.pIdx.put(sec); </pre>
<p>
Finally, if you are iterating over a collection of objects
using an <code class="classname">EntityCursor</code>, you can
update each object in turn using
<code class="methodname">EntityCursor.update()</code>. Note,
however, that you must be iterating using a
<code class="classname">PrimaryIndex</code>; this operation is not
allowed if you are using a
<code class="classname">SecondaryIndex</code>.
</p>
<p>
For example, the following iterates over every
<code class="classname">SimpleEntityClass</code> object in the entity
store, and it changes them all so that they have a
secondary index of <code class="literal">updatedskey</code>:
</p>
<pre class="programlisting">EntityCursor&lt;SimpleEntityClass&gt; sec_pcursor = sda.pIdx.entities();
for (SimpleEntityClass sec : sec_pcursor) {
sec.setSKey("updatedskey");
sec_pcursor.update(item);
}
sec_pcursor.close(); </pre>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="dpl_delete.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="persist_access.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="dpl_example.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Deleting Entity Objects </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Chapter 6. A DPL Example</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,419 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Creating Indexes</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="persist_index.html" title="Chapter 4. Working with Indices" />
<link rel="prev" href="persist_index.html" title="Chapter 4. Working with Indices" />
<link rel="next" href="persist_access.html" title="Chapter 5. Saving and Retrieving Objects" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Creating Indexes</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="persist_index.html">Prev</a> </td>
<th width="60%" align="center">Chapter 4. Working with Indices</th>
<td width="20%" align="right"> <a accesskey="n" href="persist_access.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="dplindexcreate"></a>Creating Indexes</h2>
</div>
</div>
</div>
<div class="toc">
<dl>
<dt>
<span class="sect2">
<a href="dplindexcreate.html#dplprimaryidxdecl">Declaring Primary Indexes</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="dplindexcreate.html#dplsecondaryidxdecl">Declaring Secondary Indexes</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="dplindexcreate.html#foreignkey">Foreign Key Constraints</a>
</span>
</dt>
</dl>
</div>
<p>
To create an index using the DPL, you use Java
annotations to declare which feature on the class is used
for the primary index, and which features (if any) are to
be used as secondary indexes.
</p>
<p>
All entity classes stored in the DPL must have a
primary index declared for it.
</p>
<p>
Entity classes can have zero or more secondary
indexes declared for them. There is no limit on the
number of secondary indexes that you can declare.
</p>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="dplprimaryidxdecl"></a>Declaring Primary Indexes</h3>
</div>
</div>
</div>
<p>
You declare a primary key for an entity class by
using the <code class="literal">@PrimaryKey</code>
annotation. This annotation must appear
immediately before the data member which
represents the class's primary key. For example:
</p>
<pre class="programlisting">package persist.gettingStarted;
import com.sleepycat.persist.model.Entity;
import com.sleepycat.persist.model.PrimaryKey;
@Entity
public class Vendor {
private String address;
private String bizPhoneNumber;
private String city;
private String repName;
private String repPhoneNumber;
private String state;
// Primary key is the vendor's name
// This assumes that the vendor's name is
// unique in the database.
@PrimaryKey
private String vendor;
... </pre>
<p>
For this class, the <code class="literal">vendor</code> value is set for an individual
<code class="classname">Vendor</code> class object by
the <code class="methodname">setVendorName()</code>
method. If our example code fails to set this
value before storing the object, the data
member used to store the primary key is set to a
null value. This would result in a runtime
error.
</p>
<p>
You can avoid the need to explicitly set a
value for a class's primary index by specifying
a sequence to be used for the primary key. This
results in an unique integer value being used
as the primary key for each stored object.
</p>
<p>
You declare a sequence is to be used by specifying
the <code class="literal">sequence</code> keyword to the
<code class="literal">@PrimaryKey</code> annotation. You must
also provide a name for the sequence. For example:
For example:
</p>
<pre class="programlisting">@PrimaryKey(sequence="Sequence_Namespace")
long myPrimaryKey; </pre>
</div>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="dplsecondaryidxdecl"></a>Declaring Secondary Indexes</h3>
</div>
</div>
</div>
<p>
To declare a secondary index, we use the
<code class="literal">@SecondaryKey</code> annotation. Note
that when we do this, we must declare what sort of
an index it is; that is, what is its relationship to
other data in the data store.
</p>
<p>
The <span class="emphasis"><em>kind</em></span> of indices that we
can declare are:
</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>
<code class="literal">ONE_TO_ONE</code>
</p>
<p>
This relationship indicates that
the secondary key is unique to the
object. If an object is stored with a
secondary key that already
exists in the data store, a run
time error is raised.
</p>
<p>
For example, a person object might
be stored with a primary key of a
social security number (in the US),
with a secondary key of the
person's employee number. Both
values are expected to be unique in
the data store.
</p>
</li>
<li>
<p>
<code class="literal">MANY_TO_ONE</code>
</p>
<p>
Indicates that the secondary key
may be used for multiple
objects in the data store. That is,
the key appears more than
once, but for each stored object it
can be used only once.
</p>
<p>
Consider a data store that relates
managers to employees. A given
manager will have multiple
employees, but each employee is
assumed to have just one manager.
In this case, the manager's
employee number might be a
secondary key, so that you can
quickly locate all the objects
related to that manager's
employees.
</p>
</li>
<li>
<p>
<code class="literal">ONE_TO_MANY</code>
</p>
<p>
Indicates that the secondary key
might be used more than once for a
given object. Index keys
themselves are assumed to be
unique, but multiple instances of
the index can be used per object.
</p>
<p>
For example, employees might have
multiple unique email addresses. In
this case, any given object can be
access by one or more email
addresses. Each such address is
unique in the data store, but each
such address will relate to a
single employee object.
</p>
</li>
<li>
<p>
<code class="literal">MANY_TO_MANY</code>
</p>
<p>
There can be multiple keys for
any given object, and for any given
key there can be many related
objects.
</p>
<p>
For example, suppose your
organization has a shared
resource, such as printers. You
might want to track which
printers a given employee can
use (there might be more than
one). You might also want to
track which employees can use a
specific printer. This
represents a many-to-many
relationship.
</p>
</li>
</ul>
</div>
<p>
Note that for <code class="literal">ONE_TO_ONE</code> and
<code class="literal">MANY_TO_ONE</code> relationships, you
need a simple data member (not an array or
collection) to hold the key. For
<code class="literal">ONE_TO_MANY</code> and
<code class="literal">MANY_TO_MANY</code> relationships, you
need an array or collection to hold the keys:
</p>
<pre class="programlisting">@SecondaryKey(relate=ONE_TO_ONE)
private String primaryEmailAddress = new String();
@SecondaryKey(relate=ONE_TO_MANY)
private Set&lt;String&gt; emailAddresses = new HashSet&lt;String&gt;(); </pre>
</div>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="foreignkey"></a>Foreign Key Constraints</h3>
</div>
</div>
</div>
<p>
Sometimes a secondary index is related in some
way to another entity class that is also
contained in the data store. That is, the
secondary key might be the primary key for
another entity class. If this is the case, you
can declare the foreign key constraint to make
data integrity easier to accomplish.
</p>
<p>
For example, you might have one class that is
used to represent employees.
You might have another that is used to
represent corporate divisions. When you add or
modify an employee record, you might want to
ensure that the division to which the employee
belongs is known to the data store. You do this
by specifying a foreign key constraint.
</p>
<p>
When a foreign key constraint is declared:
</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>
When a new secondary key
for the object is stored,
it is checked to make sure
it exists as a primary
key for the related
entity object. If it does
not, a runtime error
occurs.
</p>
</li>
<li>
<p>
When a related entity is
deleted (that is, a
corporate division is
removed from the data
store), some action is
automatically taken for
the entities that refer to
this object (that is, the
employee objects). Exactly
what that action is, is
definable by you. See
below.
</p>
</li>
</ul>
</div>
<p>
When a related entity is deleted from the data
store, one of the following actions are taken:
</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>
<code class="literal">ABORT</code>
</p>
<p>
The delete operation is not
allowed. A runtime error is
raised as a result of the
operation. This is the
default behavior.
</p>
</li>
<li>
<p>
<code class="literal">CASCADE</code>
</p>
<p>
All entities related to this
one are deleted as well. For
example, if you deleted a
<code class="classname">Division</code>
object, then all
<code class="classname">Employee</code>
objects that belonged to the
division are also deleted.
</p>
</li>
<li>
<p>
<code class="literal">NULLIFY</code>
</p>
<p>
All entities related to the
deleted entity are updated so
that the pertinent data member
is nullified. That is, if you
deleted a division, then all
employee objects related to
that division would have their
division key
automatically set to null.
</p>
</li>
</ul>
</div>
<p>
You declare a foreign key constraint by using
the <code class="literal">relatedEntity</code> keyword. You
declare the foreign key constraint deletion policy using the
<code class="literal">onRelatedEntityDelete</code> keyword. For
example, the following declares a foreign key
constraint to <code class="classname">Division</code>
class objects, and it causes related objects to
be deleted if the <code class="classname">Division</code>
class is deleted:
</p>
<pre class="programlisting">@SecondaryKey(relate=ONE_TO_ONE, relatedEntity=Division.class,
onRelatedEntityDelete=CASCADE)
private String division = new String(); </pre>
</div>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="persist_index.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="persist_index.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="persist_access.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Chapter 4. Working with Indices </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Chapter 5. Saving and Retrieving Objects</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,412 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Chapter 2. Database Environments</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="prev" href="logfilesrevealed.html" title="Six Things Everyone Should Know about JE Log Files" />
<link rel="next" href="envclose.html" title="Closing Database Environments" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Chapter 2. Database Environments</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="logfilesrevealed.html">Prev</a> </td>
<th width="60%" align="center"> </th>
<td width="20%" align="right"> <a accesskey="n" href="envclose.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="chapter" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title"><a id="env"></a>Chapter 2. Database Environments</h2>
</div>
</div>
</div>
<div class="toc">
<p>
<b>Table of Contents</b>
</p>
<dl>
<dt>
<span class="sect1">
<a href="env.html#envopen">Opening Database Environments</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect2">
<a href="env.html#multienv">Multiple Environments</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="env.html#multisubdir">Multiple Environment Subdirectories</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="env.html#multienvsharedcache">Configuring a Shared Cache for Multiple Environments</a>
</span>
</dt>
</dl>
</dd>
<dt>
<span class="sect1">
<a href="envclose.html">Closing Database Environments</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="EnvProps.html">Environment Properties</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect2">
<a href="EnvProps.html#envconfig">The EnvironmentConfig Class</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="EnvProps.html#envhandleconfig">EnvironmentMutableConfig</a>
</span>
</dt>
</dl>
</dd>
<dt>
<span class="sect1">
<a href="envStats.html">Environment Statistics</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="dbenvUsageExample.html">Database Environment Management Example</a>
</span>
</dt>
</dl>
</div>
<p>
Regardless of whether you are using the DPL or the base API, you must use a database
environment. Database environments encapsulate one or more databases. This encapsulation
provides your threads with efficient access to your databases by allowing a single in-memory
cache to be used for each of the databases contained in the environment. This encapsulation
also allows you to group operations performed against multiple databases inside a single
transaction (see the <em class="citetitle">Berkeley DB, Java Edition Getting Started with Transaction Processing</em> guide for more information).
</p>
<p>
If you are using the base API, most commonly you use database environments to create and
open databases (you close individual databases using the individual database handles). You
can also use environments to delete and rename databases. For transactional applications,
you use the environment to start transactions. For non-transactional applications, you use
the environment to sync your in-memory cache to disk.
</p>
<p>
If you are using the DPL, all of these things are still being done, but the DPL takes
care of it for you. Under the DPL, the most common thing you will explicitly use an
environment for is to obtain transaction handles.
</p>
<p>
Regardless of the API that you use, you also use the database environment for
administrative and configuration activities related to your database log files and the
in-memory cache.
See <a class="xref" href="administration.html" title="Chapter 12. Administering Berkeley DB Java Edition Applications">Administering Berkeley DB Java Edition Applications</a> for
more information.
</p>
<p>
To find out how to use environments with a transaction-protected application, see the
<em class="citetitle">Berkeley DB, Java Edition Getting Started with Transaction Processing</em> guide.
</p>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="envopen"></a>Opening Database Environments</h2>
</div>
</div>
</div>
<div class="toc">
<dl>
<dt>
<span class="sect2">
<a href="env.html#multienv">Multiple Environments</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="env.html#multisubdir">Multiple Environment Subdirectories</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="env.html#multienvsharedcache">Configuring a Shared Cache for Multiple Environments</a>
</span>
</dt>
</dl>
</div>
<p>
You open a database environment by instantiating an <code class="classname">Environment</code>
object. You must provide to the constructor the name of the on-disk directory where the
environment is to reside. This directory location must exist or the open will fail.
</p>
<p>
By default, the environment is not created for you if it does not exist. Set the <a class="link" href="EnvProps.html" title="Environment Properties">creation property</a> to <code class="literal">true</code> if you
want the environment to be created. For example:
</p>
<pre class="programlisting">package je.gettingStarted;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;
import java.io.File;
...
// Open the environment. Allow it to be created if it does not
// already exist.
Environment myDbEnvironment = null;
try {
EnvironmentConfig envConfig = new EnvironmentConfig();
envConfig.setAllowCreate(true);
myDbEnvironment = new Environment(new File("/export/dbEnv"),
envConfig);
} catch (DatabaseException dbe) {
// Exception handling goes here
} </pre>
<p>
Opening an environment usually causes some background threads to be started. JE uses
these threads for log file cleaning and some administrative tasks. However, these
threads will only be opened once per process, so if you open the same environment more
than once from within the same process, there is no performance impact on your
application. Also, if you open the environment as read-only, then the background
threads (with the exception of the evictor thread) are not started.
</p>
<p>
Note that opening your environment causes normal recovery to be run. This
causes your databases to be brought into a consistent state relative to the
changed data found in your log files.
See <a class="xref" href="backuprestore.html#databaselogs" title="Databases and Log Files">Databases and Log Files</a>
for more information.
</p>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="multienv"></a>Multiple Environments</h3>
</div>
</div>
</div>
<p>
Most JE applications only need a single database environment because any
number of databases can be created in a single environment, and the
total size of the data in an environment is not limited. That said,
your application can open and use as many environments as you have disk and
memory to manage. Also, you can instantiate
multiple <code class="classname">Environment</code> objects
for the same physical environment.
</p>
<p>
The main reason for multiple environments is that an application must manage
multiple unique data sets. By placing each data set in a separate environment,
the application can gain real advantages in manageability of the data, and with
application performance. By placing each data set in a unique environment,
a separate set of log files is created and maintained in a separate directory,
and so you can manipulate the log files for each data set separately.
That is, you can:
</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>
Backup, restore or delete a single data set
separately by copying or removing the files for its environment.
</p>
</li>
<li>
<p>
Balance the load between machines by moving the files for a
single data set from one machine to another.
</p>
</li>
<li>
<p>
Improve I/O performance by placing each data set on a separate
physical disk.
</p>
</li>
<li>
<p>
Delete individual data sets very efficiently by removing the
environment's log files. This is much more efficient than
deleting individual database records and is also move
efficient than removing databases, and so can be a real benefit
if you are managing large temporary data sets that must be
frequently deleted.
</p>
</li>
</ul>
</div>
<p>
Be aware that there is a downside to using multiple environments. In particular,
understand that a single transaction cannot include changes
made in more than one environment. If you need to perform a set of
operations in more than one data set atomically (with a single
transaction), use a single environment and distinguish the data sets
using some other method.
</p>
<p>
For example, an application running a hosted service for multiple clients may
wish to keep each client's data set separate. You can do this with multiple
environments, but then you can operate on all data sets atomically. If you need
to wrap operations for multiple data sets in a single transaction, consider some
other approach to keeping the data sets separate.
</p>
<p>
You can, for example, distinguish each data set using a unique key range within
a single database. Or you can create a secondary key that identifies the data
set. Or you could use separate databases for each dataset. All of these
approaches allow you to maintain multiple distinct dataset within a single
environment, but each obviously adds a level of complexity to your code over
what is required to simply use a unique environment for each data set.
</p>
</div>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="multisubdir"></a>Multiple Environment Subdirectories</h3>
</div>
</div>
</div>
<p>
You can spread your JE environment across multiple subdirectories. This allows you
to improve data throughput by spreading disk I/O across multiple disks or filesystems.
Environment subdirectories reside in the environment home directory and are named
<code class="literal">data001/</code> through <code class="literal">dataNNN/</code>, consecutively, where
<code class="literal">NNN</code> is the number of subdirectories that you want to use. Typically,
each of the <code class="literal">dataNNN/</code> names are symbolic links to actual directories
which reside on separate file systems or disks. Alternatively, each subdirectory can
be mount points for filesystems which reside on different disk drives.
</p>
<p>
You control the number of subdirectories you want to use with the
<code class="literal">je.log.nDataDirectories</code> property in the
<code class="literal">je.properties</code> file. This value must be set prior to opening the
environment, and the subdirectories must already exist at that time. The value set for
this property can not change over the course of the environment's lifetime, or an
exception is thrown when you attempt to open the environment.
</p>
<p>
The default value for <code class="literal">je.log.nDataDirectories</code> is 0, and this means no
subdirectories are in use for the environment. A value greater than 0 indicates the
number of subdirectories to use, and that number of subdirectories must exist prior to
opening the environment.
</p>
<p>
For example, if you set <code class="literal">je.log.nDataDirectories</code> to 3, then the first
time you open the environment (and for every environment open after that) your
environment home directory must contain three subdirectories named
<code class="literal">data001</code>, <code class="literal">data002</code> and <code class="literal">data003</code>.
This causes your JE log files (the <code class="literal">*.jdb</code> files) to be spread
evenly across those three subdirectories. Finally, if you change the value of
<code class="literal">je.log.nDataDirectories</code> without first completely deleting your
environment, then your application will throw exceptions when you open your environment.
</p>
</div>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="multienvsharedcache"></a>Configuring a Shared Cache for Multiple Environments</h3>
</div>
</div>
</div>
<p>
By default, each distinct JE environment has a separate, private
in-memory cache. If a single JVM process will keep open multiple
environments at the same time, it is strongly recommended that all such
environments are configured to use a shared cache. A shared cache makes
much more efficient use of memory than separate private caches.
</p>
<p>
For example, imagine that you open 5 environments in a single process
and a total of 500 MB of memory is available for caching. Using private
caches, you could configure each cache to be 100 MB. If one of the
environments has a larger active data set than the others, it will
not be able to take advantage of unused memory in the other environment
caches. By using a shared cache, multiple open environments will make
better use of memory because the cache LRU algorithm is applied across
all information in all enviornments sharing the cache.
</p>
<p>
In order to configure an environment to use a shared cache, set
<code class="methodname">EnvironmentConfig.setSharedCache()</code>
to <code class="literal">true</code>. This must be set for every environment in the
process that you want to use the shared cache. For example:
</p>
<pre class="programlisting">package je.gettingStarted;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;
import java.io.File;
...
// Open the environment. Allow it to be created if it does not
// already exist.
Environment myEnv1 = null;
Environment myEnv2 = null;
try {
EnvironmentConfig envConfig = new EnvironmentConfig();
envConfig.setAllowCreate(true);
envConfig.setSharedCache(true);
myEnv1 = new Environment(new File("/export/dbEnv1"), envConfig);
myEnv2 = new Environment(new File("/export/dbEnv2"), envConfig);
} catch (DatabaseException dbe) {
// Exception handling goes here
} </pre>
</div>
</div>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="logfilesrevealed.html">Prev</a> </td>
<td width="20%" align="center"> </td>
<td width="40%" align="right"> <a accesskey="n" href="envclose.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Six Things Everyone Should Know about JE Log Files </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Closing Database Environments</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,102 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Environment Statistics</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="env.html" title="Chapter 2. Database Environments" />
<link rel="prev" href="EnvProps.html" title="Environment Properties" />
<link rel="next" href="dbenvUsageExample.html" title="Database Environment Management Example" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Environment Statistics</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="EnvProps.html">Prev</a> </td>
<th width="60%" align="center">Chapter 2. Database Environments</th>
<td width="20%" align="right"> <a accesskey="n" href="dbenvUsageExample.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="envStats"></a>Environment Statistics</h2>
</div>
</div>
</div>
<p>
JE offers a wealth of information that you can examine regarding your environment's operations. The majority
of this information involves numbers relevant only to the JE developer and as such a description of those
statistics is beyond the scope of this manual.
</p>
<p>
However, one statistic that is very important (especially for
long-running applications) is
<code class="methodname">EnvironmentStats.getNCacheMiss()</code>.
This statistic returns the total number of
requests for database objects that were not serviceable from the cache.
This number is important to the
application administrator who is attempting to determine the proper size for the in-memory cache.
See <a class="xref" href="cachesize.html" title="Sizing the Cache">Sizing the Cache</a> for details.
</p>
<p>
To obtain this statistic from your environment, call <code class="methodname">Environment.getStats()</code> to return
an <code class="classname">EnvironmentStats</code> object. You can then call the
<code class="methodname">EnvironmentStats.getNCacheMiss()</code> method. For example:
</p>
<a id="je_env5"></a>
<pre class="programlisting">import com.sleepycat.je.Environment;
...
long cacheMisses = myEnv.getStats(null).getNCacheMiss();
...
</pre>
<p>
Note that <code class="methodname">Environment.getStats()</code> can only obtain statistics from your application's
process. In order for the application administrator to obtain this statistic, you must either
use JMX to retrieve the statistic
(see <a class="xref" href="jmx.html" title="JConsole and JMX Support">JConsole and JMX Support</a>)
or you must print it for examination (for example, log the value once a minute).
</p>
<p>
Remember that what is really important for cache sizing is the change in this value over time, and not the actual value
itself. So you might consider offering a delta from one examination of this statistic to the next (a delta of 0 is
desired while large deltas are an indication that the cache is too small).
</p>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="EnvProps.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="env.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="dbenvUsageExample.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Environment Properties </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Database Environment Management Example</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,127 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Closing Database Environments</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="env.html" title="Chapter 2. Database Environments" />
<link rel="prev" href="env.html" title="Chapter 2. Database Environments" />
<link rel="next" href="EnvProps.html" title="Environment Properties" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Closing Database Environments</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="env.html">Prev</a> </td>
<th width="60%" align="center">Chapter 2. Database Environments</th>
<td width="20%" align="right"> <a accesskey="n" href="EnvProps.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="envclose"></a>Closing Database Environments</h2>
</div>
</div>
</div>
<p>
You close your environment by calling the <code class="methodname">Environment.close()</code>
method. This method performs a checkpoint, so it is not necessary to perform a sync or a
checkpoint explicitly before calling it. For information on checkpoints, see the
<em class="citetitle">Berkeley DB, Java Edition Getting Started with Transaction Processing</em> guide. For information on syncs, see <a class="xref" href="backuprestore.html#syncs" title="Database Modifications and Syncs">Database Modifications and Syncs</a>.
</p>
<a id="je_env2"></a>
<pre class="programlisting">import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Environment;
...
try {
if (myDbEnvironment != null) {
myDbEnvironment.close();
}
} catch (DatabaseException dbe) {
// Exception handling goes here
} </pre>
<p>
If you are using the DPL, then close your environment(s) only after all other store
activities have completed and you have closed any stores currently opened in the
environment. If you are using the base API, then close your environment(s) only after
all other database activities have completed and you have closed any databases currently
opened in the environment.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;">
<h3 class="title">Note</h3>
<p>
It is possible for the environment to close before JE's
cleaner thread
has finished its work. This happens if you perform a large number of deletes immediately
before shutting down your environment. The result is that your log files may be quit a lot larger than you
expect them to be because the cleaner thread has not had a chance to finish its work.
</p>
<p>
See <a class="xref" href="backgroundthreads.html#cleaner" title="The Cleaner Thread">The Cleaner Thread</a> for
details on the cleaner threads.
</p>
<p>
If you want to make sure that the cleaner has finished running before the environment is closed,
call <code class="methodname">Environment.cleanLog()</code> before calling
<code class="methodname">Environment.close()</code>:
</p>
<a id="je_env2-1"></a>
<pre class="programlisting">import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Environment;
...
try {
if (myDbEnvironment != null) {
myDbEnvironment.cleanLog(); // Clean the log before closing
myDbEnvironment.close();
}
} catch (DatabaseException dbe) {
// Exception handling goes here
} </pre>
</div>
<p>
Closing the last environment handle in your application causes all internal data structures
to be released and the background threads to be stopped. If there are any opened databases,
then JE will complain before closing them as well. At this time, and any on-going
transactions are aborted. Also at this time any open cursors are also closed. However, it is recommended that you always close all cursor handles immediately after their use to ensure concurrency and to release resources such as page locks.
</p>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="env.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="env.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="EnvProps.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Chapter 2. Database Environments </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Environment Properties</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,336 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Retrieving Multiple Objects</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="persist_access.html" title="Chapter 5. Saving and Retrieving Objects" />
<link rel="prev" href="simpleget.html" title="Retrieving Objects from an Entity Store" />
<link rel="next" href="dpl_entityjoin.html" title="Join Cursors" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Retrieving Multiple Objects</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="simpleget.html">Prev</a> </td>
<th width="60%" align="center">Chapter 5. Saving and Retrieving Objects</th>
<td width="20%" align="right"> <a accesskey="n" href="dpl_entityjoin.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="getmultiple"></a>Retrieving Multiple Objects</h2>
</div>
</div>
</div>
<div class="toc">
<dl>
<dt>
<span class="sect2">
<a href="getmultiple.html#dpl_cursor_initialize">Cursor Initialization</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="getmultiple.html#dpl_dups">Working with Duplicate Keys</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="getmultiple.html#dpl_cursor_range">Key Ranges</a>
</span>
</dt>
</dl>
</div>
<p>
It is possible to iterate over every object referenced
by a specific index. You may want to do this if, for
example, you want to examine or modify every object
accessible by a specific primary index.
</p>
<p>
In addition, some indexes result in the retrieval of multiple
objects. For example, <code class="literal">MANY_TO_ONE</code>
secondary indexes can result in more than one object for any given
key (also known as <span class="emphasis"><em>duplicate keys</em></span>).
When this is the case, you must iterate
over the resulting set of objects in order to examine
each object in turn.
</p>
<p>
There are two ways to iterate over a collection of
objects as returned by an index. One is to use a
standard Java <code class="classname">Iterator</code>, which you
obtain using an <code class="classname">EntityCursor</code>,
which in turn you can obtain from a <code class="classname">PrimaryIndex</code>:
</p>
<pre class="programlisting">PrimaryIndex&lt;String,SimpleEntityClass&gt; pi =
store.getPrimaryIndex(String.class, SimpleEntityClass.class);
EntityCursor&lt;SimpleEntityClass&gt; pi_cursor = pi.entities();
try {
Iterator&lt;SimpleEntityClass&gt; i = pi_cursor.iterator();
while (i.hasNext()) {
// Do something here
}
} finally {
// Always close the cursor
pi_cursor.close();
} </pre>
<p>
Alternatively, you can use a Java "foreach" statement
to iterate over object set:
</p>
<pre class="programlisting">PrimaryIndex&lt;String,SimpleEntityClass&gt; pi =
store.getPrimaryIndex(String.class, SimpleEntityClass.class);
EntityCursor&lt;SimpleEntityClass&gt; pi_cursor = pi.entities();
try {
for (SimpleEntityClass seci : pi_cursor) {
// do something with each object "seci"
}
// Always make sure the cursor is closed when we are done with it.
} finally {
pi_cursor.close();
} </pre>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="dpl_cursor_initialize"></a>Cursor Initialization</h3>
</div>
</div>
</div>
<p>
When a cursor is first opened, it is not
positioned to any value; that is,
it is not <span class="emphasis"><em>initialized</em></span>.
Most of the <code class="classname">EntityCursor</code>
methods that move a cursor will initialize it
to either the first or last object, depending
on whether the operation is moving the cursor
forward (all <code class="literal">next...</code>
methods) or backwards (all
<code class="literal">prev...</code>) methods.
</p>
<p>
You can also force a cursor, whether it is
initialized or not, to return the first object
by calling
<code class="methodname">EntityCursor.first()</code>.
Similarly, you can force a return of the last
object using
<code class="methodname">EntityCursor.last()</code>.
</p>
<p>
Operations that do not move the cursor (such as
<code class="methodname">EntityCursor.current()</code>
or <code class="methodname">EntityCursor.delete()</code>
will throw an
<code class="classname">IllegalStateException</code>
when used on an uninitialized cursor.
</p>
</div>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="dpl_dups"></a>Working with Duplicate Keys</h3>
</div>
</div>
</div>
<p>
If you have duplicate secondary keys, you can return an
<code class="classname">EntityIndex</code> class object for them
using <code class="methodname">SecondaryIndex.subIndex()</code>
Then, use that object's
<code class="methodname">entities()</code>
method to obtain an <code class="classname">EntityCursor</code>
instance.
</p>
<p>
For example:
</p>
<pre class="programlisting">PrimaryIndex&lt;String,SimpleEntityClass&gt; pi =
store.getPrimaryIndex(String.class, SimpleEntityClass.class);
SecondaryIndex&lt;String,String,SimpleEntityClass&gt; si =
store.getSecondaryIndex(pi, String.class, "sKey");
EntityCursor&lt;SimpleEntityClass&gt; sec_cursor =
si.subIndex("skeyone").entities();
try {
for (SimpleEntityClass seci : sec_cursor) {
// do something with each object "seci"
}
// Always make sure the cursor is closed when we are done with it.
} finally {
sec_cursor.close(); } </pre>
<p>
Note that if you are working with duplicate keys, you can
control how cursor iteration works by using the following
<code class="classname">EntityCursor</code> methods:
</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>
<code class="methodname">nextDup()</code>
</p>
<p>
Moves the cursor to the next object with the
same key as the cursor is currently
referencing. That is, this method returns the
next duplicate object. If no such object
exists, this method returns
<code class="literal">null</code>.
</p>
</li>
<li>
<p>
<code class="methodname">prevDup()</code>
</p>
<p>
Moves the cursor to the previous object with the
same key as the cursor is currently
referencing. That is, this method returns the
previous duplicate object in the cursor's set
of objects. If no such object exists, this method returns
<code class="literal">null</code>.
</p>
</li>
<li>
<p>
<code class="methodname">nextNoDup()</code>
</p>
<p>
Moves the cursor to the next object in the
cursor's set that has a key which is different
than the key that the cursor is currently
referencing. That is, this method skips all
duplicate objects and returns the
next non-duplicate object in the cursor's set
of objects. If no such object exists, this method returns
<code class="literal">null</code>.
</p>
</li>
<li>
<p>
<code class="methodname">prevNoDup()</code>
</p>
<p>
Moves the cursor to the previous object in the
cursor's set that has a key which is different
than the key that the cursor is currently
referencing. That is, this method skips all
duplicate objects and returns the
previous non-duplicate object in the cursor's set
of objects. If no such object exists, this method returns
<code class="literal">null</code>.
</p>
</li>
</ul>
</div>
<p>
For example:
</p>
<pre class="programlisting">PrimaryIndex&lt;String,SimpleEntityClass&gt; pi =
store.getPrimaryIndex(String.class, SimpleEntityClass.class);
SecondaryIndex&lt;String,String,SimpleEntityClass&gt; si =
store.getSecondaryIndex(pi, String.class, "sKey");
EntityCursor&lt;SimpleEntityClass&gt; sec_cursor =
si.subIndex("skeyone").entities();
try {
SimpleEntityClass sec;
Iterator&lt;SimpleEntityClass&gt; i = sec_cursor.iterator();
while (sec = i.nextNoDup() != null) {
// Do something here
}
// Always make sure the cursor is closed when we are done with it.
} finally {
sec_cursor.close(); } </pre>
</div>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="dpl_cursor_range"></a>Key Ranges</h3>
</div>
</div>
</div>
<p>
You can restrict the scope of a cursor's movement
by specifying a <span class="emphasis"><em>range</em></span> when you
create the cursor. The cursor can then never be
positioned outside of the specified range.
</p>
<p>
When specifying a range, you indicate whether a
range bound is <span class="emphasis"><em>inclusive</em></span> or
<span class="emphasis"><em>exclusive</em></span> by providing a
boolean value for each range.
<code class="literal">true</code> indicates that the provided
bound is inclusive, while <code class="literal">false</code>
indicates that it is exclusive.
</p>
<p>
You provide this information when you call
<code class="classname">PrimaryIndex.entities()</code>
or
<code class="classname">SecondaryIndex.entities()</code>.
For example, suppose you had a class indexed by
numerical information. Suppose further that you
wanted to examine only those objects with indexed
values of 100 - 199. Then (assuming the numerical
information is the primary index), you can bound
your cursor as follows:
</p>
<pre class="programlisting">
EntityCursor&lt;SomeEntityClass&gt; cursor =
primaryIndex.entities(100, true, 200, false);
try {
for (SomeEntityClass sec : cursor {
// Do something here to objects ranged from 100 to 199
}
// Always make sure the cursor is closed when we are done with it.
} finally {
cursor.close(); } </pre>
</div>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="simpleget.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="persist_access.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="dpl_entityjoin.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Retrieving Objects from an Entity Store </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Join Cursors</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,50 @@
body { width: 45em;
margin-left: 3em;
font-family: Arial, Helvetica, sans-serif;
font-size: 11pt;
}
h2.title { margin-left: -1em;
font-family: Verdana, serif;
font-size: 16pt;
}
h3.title { font-family: Verdana, serif;
font-size: 14pt;
}
pre.programlisting {
font-family: monospace;
background-color: #eae8e9;
}
div.navheader { font-size: 10pt;
width: 60em;
margin-left: -2em;
}
div.navheader table tr td { font-size: 10pt; }
div.navfooter { font-size: 10pt;
width: 60em;
margin-left: -2em;
}
div.navfooter table tr td { font-size: 10pt; }
span.emphasis { font-style: italic;}
div.appendix div.informaltable { font-size: 9pt; }
div.appendix div.informaltable td { vertical-align: top; }
div.appendix div.informaltable p { margin-top: .25em; }
div.appendix div.informaltable p { margin-bottom: .25em; }
div.variablelist dl dt {margin-top: 1em; }
div.libver p {
font-size: 8pt;
width: 30%;
margin-left: 2px;
margin-right: 2px;
padding-top: 3px;
padding-bottom: 3px;
}

View file

@ -0,0 +1,103 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Getting and Using JE</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="introduction.html" title="Chapter 1. Introduction to Berkeley DB Java Edition" />
<link rel="prev" href="jmx.html" title="JConsole and JMX Support" />
<link rel="next" href="jeexceptions.html" title="JE Exceptions" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Getting and Using JE </th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="jmx.html">Prev</a> </td>
<th width="60%" align="center">Chapter 1. Introduction to Berkeley DB Java Edition </th>
<td width="20%" align="right"> <a accesskey="n" href="jeexceptions.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="gettingit"></a>Getting and Using JE </h2>
</div>
</div>
</div>
<p>
You can obtain JE by visiting the JE download page: <a class="ulink" href="http://www.oracle.com/technetwork/database/database-technologies/berkeleydb/downloads/index.html" target="_top">http://www.oracle.com/technetwork/database/database-technologies/berkeleydb/downloads/index.html</a>.
</p>
<p>
To install JE, untar or unzip the distribution to the
directory of your choice. If you use unzip, make sure to specify
the <code class="literal">-U</code> option in order to preserve case.
</p>
<p>
For more information on installing JE, see
<span class="emphasis"><em>JE_HOME</em></span><code class="literal">/docs/relnotes.html</code>,
where <span class="emphasis"><em>JE_HOME</em></span> is the directory where you
unpacked JE.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;">
<h3 class="title">Note</h3>
<p>
JE is compatible with Java SE 8 (64-bit), and has been
tested and certified against Oracle Java SE 8 and IBM Java IBM
J9. It is recommended that you upgrade to the latest Java
releases to take advantage of the latest bug fixes and
performance improvements. The release notes included in the
JE download specify the exact Java versions that have been
used for certification.
</p>
<p>
Linux, Oracle Solaris, and AIX are officially supported platforms for
JE. Both Oracle Solaris x86 and Oracle Solaris SPARC are
supported. A 64 bit JVM is required in order to run JE.
</p>
</div>
<p>
You can use JE with your application by adding
<span class="emphasis"><em>JE_HOME</em></span><code class="literal">/lib/je-&lt;version&gt;.jar</code>
to your application's classpath.
</p>
<p>
Beyond this manual, you can find documentation for JE at
<span class="emphasis"><em>JE_HOME</em></span><code class="literal">/docs/index.html</code>
directory. In particular, complete Javadoc for the JE API set
is available at
<span class="emphasis"><em>JE_HOME</em></span><code class="literal">/docs/java/index.html</code>.
</p>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="jmx.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="introduction.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="jeexceptions.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">JConsole and JMX Support </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> JE Exceptions</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,128 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Hot Standby</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="backuprestore.html" title="Chapter 11. Backing up and Restoring Berkeley DB Java Edition Applications" />
<link rel="prev" href="catastrophicrecovery.html" title="Performing Catastrophic Recovery" />
<link rel="next" href="administration.html" title="Chapter 12. Administering Berkeley DB Java Edition Applications" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Hot Standby</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="catastrophicrecovery.html">Prev</a> </td>
<th width="60%" align="center">Chapter 11. Backing up and Restoring Berkeley DB Java Edition Applications</th>
<td width="20%" align="right"> <a accesskey="n" href="administration.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="hotfailover"></a>Hot Standby</h2>
</div>
</div>
</div>
<p>
As a final backup/recovery strategy, you can create a hot standby. Note that using hot standbys requires
your application to be able to specify its environment home directory at application startup time. Most
application developers allow the environment home directory to be identified using a command line option or a
configuration or properties file. If your application has its
environment home hard-coded into it, you cannot use hot standbys.
</p>
<p>
You create a hot standby by periodically backing up your database to an alternative
location on disk. Usually this alternative location is on a separate physical drive from
where you normally keep your database, but if multiple drives are not available then you
should at least put the hot standby on a separate disk partition.
</p>
<p>
You failover to your hot standby by causing your application to reopen its environment using the hot standby
location.
</p>
<p>
Note that a hot standby should not be used as a substitute for backing up and archiving your data to a safe
location away from your operating environment. Even if your data is spread across multiple physical disks, a
truly serious catastrophe (fires, malevolent software viruses,
faulty disk controllers, and so forth)
can still cause you to lose your data.
</p>
<p>
To create and maintain a hot standby:
</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>
Copy all log files (<code class="filename">*.jdb</code>) from your environment
directory to the location where you want to keep your standby. Either a hot
or an offline backup can be used for this purpose, but typically a hot
standby is initially created by taking an offline backup of your database.
This ensures that you have captured the contents of your in-memory cache.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;">
<h3 class="title">Note</h3>
<p>
If you are using subdirectories to store your log files, then you must backup
the subdirectories, making sure to keep log files in the subdirectory in which
JE placed them. For information on using subdirectories to store your log
files, see <a class="xref" href="env.html#multisubdir" title="Multiple Environment Subdirectories">Multiple Environment Subdirectories</a>.
</p>
</div>
</li>
<li>
<p>
Periodically copy to your standby directory any log files that were changed or created since the
time of your last copy. Most backup software is capable of performing this kind of an incremental
backup for you.
</p>
<p>
Note that the frequency of your incremental copies determines the amount of data that is at risk due to catastrophic
failures. For example, if you perform the incremental copy once an hour then at most your hot standby is an hour behind
your production database, and so you are risking at most an hours worth of database changes.
</p>
</li>
<li>
<p>
Remove any <code class="filename">*.jdb</code> files from the hot standby directory that have been removed or
renamed to <code class="filename">.del</code> files in the primary directory. This is not necessary for
consistency, but will help to reduce disk space consumed by the hot standby.
</p>
</li>
</ol>
</div>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="catastrophicrecovery.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="backuprestore.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="administration.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Performing Catastrophic Recovery </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Chapter 12. Administering Berkeley DB Java Edition Applications</td>
</tr>
</table>
</div>
</body>
</html>

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,398 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Chapter 10. Secondary Databases</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="baseapi.html" title="Part II. Programming with the Base API" />
<link rel="prev" href="cursorUsage.html" title="Cursor Example" />
<link rel="next" href="keyCreator.html" title="Implementing Key Creators" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Chapter 10. Secondary Databases</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="cursorUsage.html">Prev</a> </td>
<th width="60%" align="center">Part II. Programming with the Base API</th>
<td width="20%" align="right"> <a accesskey="n" href="keyCreator.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="chapter" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title"><a id="indexes"></a>Chapter 10. Secondary Databases</h2>
</div>
</div>
</div>
<div class="toc">
<p>
<b>Table of Contents</b>
</p>
<dl>
<dt>
<span class="sect1">
<a href="indexes.html#DbAssociate">Opening and Closing Secondary Databases</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="keyCreator.html">Implementing Key
<span>Creators</span>
</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="secondaryProps.html">Secondary Database Properties</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="readSecondary.html">Reading Secondary Databases</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="secondaryDelete.html">Deleting Secondary Database Records</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="secondaryCursor.html">
<span>Using Secondary Cursors</span>
</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="joins.html">Database Joins</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect2">
<a href="joins.html#joinUsage">Using Join Cursors</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="joins.html#joinconfig">JoinCursor Properties</a>
</span>
</dt>
</dl>
</dd>
<dt>
<span class="sect1">
<a href="indexusage.html">Secondary Database Example</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect2">
<a href="indexusage.html#secondaryMyDbEnv">Opening Secondary Databases with
MyDbEnv</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="indexusage.html#exampleReadSecondaries">Using Secondary Databases with ExampleInventoryRead</a>
</span>
</dt>
</dl>
</dd>
</dl>
</div>
<p>
Usually you find database records by means of the record's key. However,
the key that you use for your record will not always contain the
information required to provide you with rapid access to the data that you
want to retrieve. For example, suppose your
<code class="classname">Database</code>
contains records related to users. The key might be a string that is some
unique identifier for the person, such as a user ID. Each record's data,
however, would likely contain a complex object containing details about
people such as names, addresses, phone numbers, and so forth.
While your application may frequently want to query a person by user
ID (that is, by the information stored in the key), it may also on occasion
want to locate people by, say, their name.
</p>
<p>
Rather than iterate through all of the records in your database, examining
each in turn for a given person's name, you create indexes based on names
and then just search that index for the name that you want. You can do this
using secondary databases. In JE, the
<code class="classname">Database</code>
that contains your data is called a
<span class="emphasis"><em>primary database</em></span>. A database that provides an
alternative set of keys to access that data is called a <span class="emphasis"><em>secondary
database</em></span><span>,
and these are managed using <code class="classname">SecondaryDatabase</code>
class objects.</span> In a secondary database, the keys are your alternative
(or secondary) index, and the data corresponds to a primary record's key.
</p>
<p>
You create a secondary database by using a <code class="classname">SecondaryConfig</code>
class object to identify an implementation of a
<code class="classname">SecondaryKeyCreator</code>
class object that is used to create keys based on data found in the primary
database. You then pass this <code class="classname">SecondaryConfig</code>
object to the <code class="classname">SecondaryDatabase</code> constructor.
</p>
<p>
Once opened, JE manages secondary databases for you. Adding or deleting
records in your primary database causes JE to update the secondary as
necessary. Further, changing a record's data in the primary database may cause
JE to modify a record in the secondary, depending on whether the change
forces a modification of a key in the secondary database.
</p>
<p>
Note that you can not write directly to a secondary database.
<span>While methods
exist on <code class="classname">SecondaryDatabase</code> and
<code class="classname">SecondaryCursor</code> that appear to allow this, they in
fact always throw
<code class="classname">UnsupportedOperationException</code>.</span>
To change the data referenced by a
<code class="classname">SecondaryDatabase</code>
record, modify the primary database instead. The exception to this rule is
that delete operations are allowed on the
<span><code class="classname">SecondaryDatabase</code> object.</span>
See <a class="xref" href="secondaryDelete.html" title="Deleting Secondary Database Records">Deleting Secondary Database Records</a> for more
information.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;">
<h3 class="title">Note</h3>
<p>
Secondary database records are updated/created by JE
only if the
<span><code class="methodname">SecondaryKeyCreator.createSecondaryKey()</code> method</span>
returns
<span><code class="literal">true</code>.</span>
If
<code class="literal">false</code>
is returned, then JE will not add the key to the secondary database, and
in the event of a record update it will remove any existing key.
</p>
<p>
See <a class="xref" href="keyCreator.html" title="Implementing Key Creators">Implementing Key
<span>Creators</span>
</a> for more
<span>information on this interface and method.</span>
</p>
</div>
<p>
When you read a record from a secondary database, JE automatically
returns
<span>the key and data</span>
from the corresponding record in the primary database.
<span>
</span>
</p>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="DbAssociate"></a>Opening and Closing Secondary Databases</h2>
</div>
</div>
</div>
<p>
You manage secondary database opens and closes using the
<span>
<code class="methodname">Environment.openSecondaryDatabase()</code> method.
</span>
Just as is the case with primary databases, you must provide
<code class="methodname">Environment.openSecondaryDatabase()</code>
with the database's
name and, optionally, other properties such as whether duplicate
records are allowed, or whether the secondary database can be created on
open. In addition, you must also provide:
</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>A handle to the primary database that this secondary database is
indexing. Note that this means that secondary databases are maintained
only for the specified <code class="classname">Database</code> handle. If you
open the same <code class="classname">Database</code> multiple times for write
(such as might occur when opening a database for read-only and read-write in the same application),
then you should open the <code class="classname">SecondaryDatabase</code> for
each such <code class="classname">Database</code> handle.</p>
</li>
<li>
<p>A <code class="classname">SecondaryConfig</code> object that provides
properties specific to a secondary database. The most important of
these is used to identify the key creator for the database. The key
creator is responsible for generating keys for the secondary database.
See <a class="xref" href="secondaryProps.html" title="Secondary Database Properties">Secondary Database Properties</a> for details.</p>
</li>
</ul>
</div>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;">
<h3 class="title">Note</h3>
<p>
Primary databases <span class="emphasis"><em>must not</em></span> support duplicate records.
Secondary records point to primary records using the primary key, so that key must be unique.
</p>
</div>
<p>So to open (create) a secondary database, you:</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>Open your primary database.</p>
</li>
<li>
<p>Instantiate your key creator.</p>
</li>
<li>
<p>Instantiate your <code class="classname">SecondaryConfig</code> object.</p>
</li>
<li>
<p>Set your key creator object on your <code class="classname">SecondaryConfig</code>
object.</p>
</li>
<li>
<p>Open your secondary database, specifying your primary database
and your <code class="classname">SecondaryConfig</code> at that time.</p>
</li>
</ol>
</div>
<p>For example:</p>
<a id="je_index1"></a>
<pre class="programlisting">package je.gettingStarted;
import com.sleepycat.bind.tuple.TupleBinding;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseConfig;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Environment;
import com.sleepycat.je.SecondaryDatabase;
import com.sleepycat.je.SecondaryConfig;
import java.io.File;
...
DatabaseConfig myDbConfig = new DatabaseConfig();
SecondaryConfig mySecConfig = new SecondaryConfig();
myDbConfig.setAllowCreate(true);
mySecConfig.setAllowCreate(true);
// Duplicates are frequently required for secondary databases.
mySecConfig.setSortedDuplicates(true);
// Open the primary
Environment myEnv = null;
Database myDb = null;
SecondaryDatabase mySecDb = null;
try {
String dbName = "myPrimaryDatabase";
myEnv = new Environment(new File("/tmp/JEENV"), null);
myDb = myEnv.openDatabase(null, dbName, myDbConfig);
// A fake tuple binding that is not actually implemented anywhere
// in this manual. The tuple binding is dependent on the data in use.
// Tuple bindings are described earlier in this manual.
TupleBinding myTupleBinding = new MyTupleBinding();
// Open the secondary.
// Key creators are described in the next section.
FullNameKeyCreator keyCreator =
new FullNameKeyCreator(myTupleBinding);
// Get a secondary object and set the key creator on it.
mySecConfig.setKeyCreator(keyCreator);
// Perform the actual open
String secDbName = "mySecondaryDatabase";
mySecDb = myEnv.openSecondaryDatabase(null, secDbName, myDb,
mySecConfig);
} catch (DatabaseException de) {
// Exception handling goes here ...
}</pre>
<p>To close a secondary database, call its close() method. Note that
for best results, you should close all the secondary databases associated
with a primary database before closing the primary.</p>
<p>For example:</p>
<a id="je_index2"></a>
<pre class="programlisting">try {
if (mySecDb != null) {
mySecDb.close();
}
if (myDb != null) {
myDb.close();
}
if (myEnv != null) {
myEnv.close();
}
} catch (DatabaseException dbe) {
// Exception handling goes here
}</pre>
</div>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="cursorUsage.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="baseapi.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="keyCreator.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Cursor Example </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Implementing Key
<span>Creators</span>
</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,483 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Secondary Database Example</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="indexes.html" title="Chapter 10. Secondary Databases" />
<link rel="prev" href="joins.html" title="Database Joins" />
<link rel="next" href="admin.html" title="Part III. Administering JE Applications" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Secondary Database Example</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="joins.html">Prev</a> </td>
<th width="60%" align="center">Chapter 10. Secondary Databases</th>
<td width="20%" align="right"> <a accesskey="n" href="admin.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="indexusage"></a>Secondary Database Example</h2>
</div>
</div>
</div>
<div class="toc">
<dl>
<dt>
<span class="sect2">
<a href="indexusage.html#secondaryMyDbEnv">Opening Secondary Databases with
MyDbEnv</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="indexusage.html#exampleReadSecondaries">Using Secondary Databases with ExampleInventoryRead</a>
</span>
</dt>
</dl>
</div>
<p>In previous chapters in this book, we built applications that load
and display several JE databases. In this example, we will extend those
examples to use secondary databases. Specifically:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>In <a class="xref" href="dbtUsage.html#dbenvStoredClass" title="Example 8.4 Stored Class Catalog Management with MyDbEnv">Stored Class Catalog Management with MyDbEnv</a> we built a
class that we can use to open and manage a
JE <code class="classname">Environment</code> and one or more <code class="classname">Database</code> objects.
In <a class="xref" href="indexusage.html#secondaryMyDbEnv" title="Opening Secondary Databases with MyDbEnv">Opening Secondary Databases with
MyDbEnv</a> we will extend
that class to also open and manage a <code class="classname">SecondaryDatabase</code>.
</p>
</li>
<li>
<p>In <a class="xref" href="cursorUsage.html" title="Cursor Example">Cursor Example</a> we
built an application to display our inventory database (and related
vendor information). In <a class="xref" href="indexusage.html#exampleReadSecondaries" title="Using Secondary Databases with ExampleInventoryRead">Using Secondary Databases with ExampleInventoryRead</a> we will extend that application to
show inventory records based on the index we cause to be loaded using
<code class="classname">ExampleDatabasePut</code>.
</p>
</li>
</ul>
</div>
<p>
Before we can use a secondary database, we must implement a class to extract secondary keys for us.
We use <code class="classname">ItemNameKeyCreator</code> for this purpose.
</p>
<div class="example">
<a id="ItemNameKeyCreator"></a>
<p class="title">
<b>Example 10.1 ItemNameKeyCreator.java</b>
</p>
<div class="example-contents">
<p>
This class assumes the primary database
uses <code class="classname">Inventory</code> objects for the record data. The
<code class="classname">Inventory</code> class is described in <a class="xref" href="dbtUsage.html#inventory" title="Example 8.1 Inventory.java">Inventory.java</a>.</p>
<p>In our key creator class, we make use of a custom tuple binding
called <code class="classname">InventoryBinding</code>. This class is described in <a class="xref" href="dbtUsage.html#InventoryBinding" title="Example 8.3 InventoryBinding.java">InventoryBinding.java</a>.</p>
<p>You can find the following class in: </p>
<pre class="programlisting"><span class="emphasis"><em>JE_HOME</em></span>/examples/je/gettingStarted/ItemNameKeyCreator.java</pre>
<p>
where <code class="literal"><span class="emphasis"><em>JE_HOME</em></span></code> is the location where you
placed your JE distribution.
</p>
<a id="je_index11"></a>
<pre class="programlisting">package je.gettingStarted;
import com.sleepycat.bind.tuple.TupleBinding;
import com.sleepycat.db.SecondaryKeyCreator;
import com.sleepycat.db.DatabaseEntry;
import com.sleepycat.db.DatabaseException;
import com.sleepycat.db.SecondaryDatabase;
public class ItemNameKeyCreator implements SecondaryKeyCreator {
private TupleBinding theBinding;
// Use the constructor to set the tuple binding
ItemNameKeyCreator(TupleBinding binding) {
theBinding = binding;
}
// Abstract method that we must implement
public boolean createSecondaryKey(SecondaryDatabase secDb,
DatabaseEntry keyEntry, // From the primary
DatabaseEntry dataEntry, // From the primary
DatabaseEntry resultEntry) // set the key data on this.
throws DatabaseException {
if (dataEntry != null) {
// Convert dataEntry to an Inventory object
Inventory inventoryItem =
(Inventory)theBinding.entryToObject(dataEntry);
// Get the item name and use that as the key
String theItem = inventoryItem.getItemName();
resultEntry.setData(theItem.getBytes());
}
return true;
}
} </pre>
</div>
</div>
<br class="example-break" />
<p>Now that we have a key creator, we can use it to generate keys for a secondary database. We will now extend
<code class="classname">MyDbEnv</code> to manage a secondary database, and to use <code class="classname">ItemNameKeyCreator</code>
to generate keys for that secondary database.
</p>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="secondaryMyDbEnv"></a>Opening Secondary Databases with
MyDbEnv</h3>
</div>
</div>
</div>
<p>In <a class="xref" href="dbtUsage.html#dbenvStoredClass" title="Example 8.4 Stored Class Catalog Management with MyDbEnv">Stored Class Catalog Management with MyDbEnv</a> we built
<code class="classname">MyDbEnv</code> as an example of a class that
encapsulates <code class="classname">Environment</code> and
<code class="classname">Database</code> opens and closes. We will now extend
that class to manage a <code class="classname">SecondaryDatabase</code>.</p>
<div class="example">
<a id="mydbenvSecondary"></a>
<p class="title">
<b>Example 10.2 SecondaryDatabase Management with MyDbEnv</b>
</p>
<div class="example-contents">
<p>We start by importing two additional classes needed to support secondary databases.
We also add a global variable to use as a handle for our secondary database.
</p>
<a id="je_index12"></a>
<pre class="programlisting">// File MyDbEnv.java
package je.gettingStarted;
import com.sleepycat.bind.tuple.TupleBinding;
import com.sleepycat.bind.serial.StoredClassCatalog;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseConfig;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;
<strong class="userinput"><code>import com.sleepycat.je.SecondaryConfig;</code></strong>
<strong class="userinput"><code>import com.sleepycat.je.SecondaryDatabase;</code></strong>
import java.io.File;
public class MyDbEnv {
private Environment myEnv;
// The databases that our application uses
private Database vendorDb;
private Database inventoryDb;
private Database classCatalogDb;
<strong class="userinput"><code>private SecondaryDatabase itemNameIndexDb;</code></strong>
// Needed for object serialization
private StoredClassCatalog classCatalog;
// Our constructor does nothing
public MyDbEnv() {}</pre>
<p>
Next we update the <code class="methodname">MyDbEnv.setup()</code> method to open the
secondary database. As a part of this, we have to pass an
<code class="classname">ItemNameKeyCreator</code> object on the call to open the secondary
database. Also, in order to instantiate <code class="classname">ItemNameKeyCreator</code>, we need an
<code class="classname">InventoryBinding</code> object (we described this class in <a class="xref" href="dbtUsage.html#InventoryBinding" title="Example 8.3 InventoryBinding.java">InventoryBinding.java</a>). We do all this work together inside of
<code class="methodname">MyDbEnv.setup()</code>.
</p>
<a id="je_index13"></a>
<pre class="programlisting"> public void setup(File envHome, boolean readOnly)
throws DatabaseException {
EnvironmentConfig myEnvConfig = new EnvironmentConfig();
DatabaseConfig myDbConfig = new DatabaseConfig();
<strong class="userinput"><code>SecondaryConfig mySecConfig = new SecondaryConfig();</code></strong>
// If the environment is read-only, then
// make the databases read-only too.
myEnvConfig.setReadOnly(readOnly);
myDbConfig.setReadOnly(readOnly);
<strong class="userinput"><code>mySecConfig.setReadOnly(readOnly);</code></strong>
// If the environment is opened for write, then we want to be
// able to create the environment and databases if
// they do not exist.
myEnvConfig.setAllowCreate(!readOnly);
myDbConfig.setAllowCreate(!readOnly);
<strong class="userinput"><code>mySecConfig.setAllowCreate(!readOnly);</code></strong>
...
// Environment and database opens omitted for brevity
...
<strong class="userinput"><code>// Open the secondary database. We use this to create a
// secondary index for the inventory database
// We want to maintain an index for the inventory entries based
// on the item name. So, instantiate the appropriate key creator
// and open a secondary database.
ItemNameKeyCreator keyCreator =
new ItemNameKeyCreator(new InventoryBinding());
// Set up the secondary properties
mySecConfig.setAllowPopulate(true); // Allow autopopulate
mySecConfig.setKeyCreator(keyCreator);
// Need to allow duplicates for our secondary database
mySecConfig.setSortedDuplicates(true);
// Now open it
itemNameIndexDb =
myEnv.openSecondaryDatabase(
null,
"itemNameIndex", // Index name
inventoryDb, // Primary database handle. This is
// the db that we're indexing.
mySecConfig); // The secondary config</code></strong>
} </pre>
<p>
Next we need an additional getter method for returning the secondary database.
</p>
<a id="je_index14"></a>
<pre class="programlisting"> public SecondaryDatabase getNameIndexDB() {
return itemNameIndexDb;
} </pre>
<p>Finally, we need to update the <code class="methodname">MyDbEnv.close()</code>
method to close the new secondary database. We want to make sure that
the secondary is closed before the primaries. While
this is not necessary for this example because our
closes are single-threaded, it is still a good habit to adopt.</p>
<a id="je_index15"></a>
<pre class="programlisting"> public void close() {
if (myEnv != null) {
try {
//Close the secondary before closing the primaries
<strong class="userinput"><code>itemNameIndexDb.close();</code></strong>
vendorDb.close();
inventoryDb.close();
classCatalogDb.close();
// Finally, close the environment.
myEnv.close();
} catch(DatabaseException dbe) {
System.err.println("Error closing MyDbEnv: " +
dbe.toString());
System.exit(-1);
}
}
}
} </pre>
<p>That completes our update to <code class="classname">MyDbEnv</code>. You
can find the complete class implementation in:
</p>
<pre class="programlisting"><span class="emphasis"><em>JE_HOME</em></span>/examples/je/gettingStarted/MyDbEnv.java </pre>
<p>
where <code class="literal"><span class="emphasis"><em>JE_HOME</em></span></code> is the location where you
placed your JE distribution.
</p>
</div>
</div>
<br class="example-break" />
</div>
<p>Because we performed all our secondary database configuration management in
<code class="classname">MyDbEnv</code>, we do not need to modify <code class="classname">ExampleDatabasePut</code> at all in
order to create our secondary indices. When <code class="classname">ExampleDatabasePut</code> calls
<code class="methodname">MyDbEnv.setup()</code>, all of the necessary work is performed for us.
</p>
<p>
However, we still need to take advantage of the new secondary indices. We do this by updating
<code class="classname">ExampleInventoryRead</code> to allow us to query for an inventory record based on its name.
Remember that the primary key for an inventory record is the item's SKU. The item's name is contained in the
<code class="classname">Inventory</code> object that is stored as each record's data in the inventory database. But
our new secondary index now allows us to easily query based on the item's name.
</p>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="exampleReadSecondaries"></a>Using Secondary Databases with ExampleInventoryRead</h3>
</div>
</div>
</div>
<p>In the previous section we changed <code class="classname">MyDbEnv</code>
to cause a secondary database to be built using inventory item names as
the secondary keys. In this section, we will update
<code class="classname">ExampleInventoryRead</code> to allow us to query our
inventory records based on the item name. To do this, we will modify
<code class="classname">ExampleInventoryRead</code> to accept a new command line switch,
<code class="literal">-s</code>, whose argument is the name of an inventory item.
If the switch is present on the command line call to
<code class="classname">ExampleInventoryRead</code>, then the application will
use the secondary database to look up and display all the inventory
records with that item name. Note that we use a <code class="classname">SecondaryCursor</code>
to seek to the item name key and then display all matching records.</p>
<p>Remember that you can find the following class in: </p>
<pre class="programlisting"><span class="emphasis"><em>JE_HOME</em></span>/examples/je/gettingStarted/ExampleInventoryRead.java</pre>
<p>
where <code class="literal"><span class="emphasis"><em>JE_HOME</em></span></code> is the location where you
placed your JE distribution.
</p>
<div class="example">
<a id="secondaryWithEIR"></a>
<p class="title">
<b>Example 10.3 SecondaryDatabase usage with ExampleInventoryRead</b>
</p>
<div class="example-contents">
<p>First we need to import a few additional classes in order to use
secondary databases and cursors, and then we add a single global variable:</p>
<a id="je_index16"></a>
<pre class="programlisting">package je.gettingStarted;
import com.sleepycat.je.Cursor;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.LockMode;
import com.sleepycat.je.OperationStatus;
<strong class="userinput"><code>import com.sleepycat.je.SecondaryCursor;</code></strong>
import com.sleepycat.bind.EntryBinding;
import com.sleepycat.bind.serial.SerialBinding;
import com.sleepycat.bind.tuple.TupleBinding;
import java.io.File;
import java.io.IOException;
public class ExampleInventoryRead {
private static File myDbEnvPath =
new File("/tmp/JEDB");
// Encapsulates the database environment and databases.
private static MyDbEnv myDbEnv = new MyDbEnv();
private static TupleBinding inventoryBinding;
private static EntryBinding vendorBinding;
<strong class="userinput"><code>// The item to locate if the -s switch is used
private static String locateItem;</code></strong> </pre>
<p>Next we update <code class="methodname">ExampleInventoryRead.run()</code> to
check to see if the <code class="literal">locateItem</code> global variable a
value. If it does, then we show just those records related to the item
name passed on the <code class="literal">-s</code> switch.</p>
<a id="je_index18"></a>
<pre class="programlisting"> private void run(String args[])
throws DatabaseException {
// Parse the arguments list
parseArgs(args);
myDbEnv.setup(myDbEnvPath, // path to the environment home
true); // is this environment read-only?
// Setup our bindings.
inventoryBinding = new InventoryBinding();
vendorBinding =
new SerialBinding(myDbEnv.getClassCatalog(),
Vendor.class);
<strong class="userinput"><code>if (locateItem != null) {
showItem();
} else {</code></strong>
showAllInventory();
<strong class="userinput"><code>}</code></strong>
} </pre>
<p>
Finally, we need to implement <code class="methodname">ExampleInventoryRead.showItem()</code>.
This is a fairly simple method that opens a secondary cursor,
and then displays every primary record that is related to the secondary
key identified by the <code class="literal">locateItem</code> global variable.
</p>
<a id="je_index19"></a>
<pre class="programlisting"> private void showItem() throws DatabaseException {
SecondaryCursor secCursor = null;
try {
// searchKey is the key that we want to find in the
// secondary db.
DatabaseEntry searchKey =
new DatabaseEntry(locateItem.getBytes("UTF-8"));
// foundKey and foundData are populated from the primary
// entry that is associated with the secondary db key.
DatabaseEntry foundKey = new DatabaseEntry();
DatabaseEntry foundData = new DatabaseEntry();
// open a secondary cursor
secCursor =
myDbEnv.getNameIndexDB().openSecondaryCursor(null, null);
// Search for the secondary database entry.
OperationStatus retVal =
secCursor.getSearchKey(searchKey, foundKey,
foundData, LockMode.DEFAULT);
// Display the entry, if one is found. Repeat until no more
// secondary duplicate entries are found
while(retVal == OperationStatus.SUCCESS) {
Inventory theInventory =
(Inventory)inventoryBinding.entryToObject(foundData);
displayInventoryRecord(foundKey, theInventory);
retVal = secCursor.getNextDup(searchKey, foundKey,
foundData, LockMode.DEFAULT);
}
} catch (Exception e) {
System.err.println("Error on inventory secondary cursor:");
System.err.println(e.toString());
e.printStackTrace();
} finally {
if (secCursor != null) {
secCursor.close();
}
}
}</pre>
<p>The only other thing left to do is to update
<code class="methodname">ExampleInventoryRead.parseArgs()</code> to support the <code class="literal">-s</code> command
line switch. To see how this is done, see:
</p>
<pre class="programlisting"><span class="emphasis"><em>JE_HOME</em></span>/examples/je/gettingStarted/ExampleInventoryRead.java</pre>
<p>
where <code class="literal"><span class="emphasis"><em>JE_HOME</em></span></code> is the location where you
placed your JE distribution.
</p>
</div>
</div>
<br class="example-break" />
</div>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="joins.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="indexes.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="admin.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Database Joins </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Part III. Administering JE Applications</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,616 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Chapter 1. Introduction to Berkeley DB Java Edition</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="prev" href="moreinfo.html" title="For More Information" />
<link rel="next" href="applicationoverview.html" title="The JE Application" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Chapter 1. Introduction to Berkeley DB Java Edition </th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="moreinfo.html">Prev</a> </td>
<th width="60%" align="center"> </th>
<td width="20%" align="right"> <a accesskey="n" href="applicationoverview.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="chapter" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title"><a id="introduction"></a>Chapter 1. Introduction to Berkeley DB Java Edition </h2>
</div>
</div>
</div>
<div class="toc">
<p>
<b>Table of Contents</b>
</p>
<dl>
<dt>
<span class="sect1">
<a href="introduction.html#features">Features</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect2">
<a href="introduction.html#dplfeatures">DPL Features</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="introduction.html#basefeatures">Base API Features</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="introduction.html#whichapi">Which API Should You Use?</a>
</span>
</dt>
</dl>
</dd>
<dt>
<span class="sect1">
<a href="applicationoverview.html">The JE Application</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect2">
<a href="applicationoverview.html#dbIntro">Database Environments</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="applicationoverview.html#key-data">Key-Data Pairs</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="applicationoverview.html#storing-intro">Storing Data</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="applicationoverview.html#duplicatesintro">Duplicate Data</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="applicationoverview.html#replacedeleteIntro">Replacing and Deleting Entries</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="applicationoverview.html#secondary">Secondary Keys</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="applicationoverview.html#transactionIntro">Transactions</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="applicationoverview.html#resourcesIntro">JE Resources</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="applicationoverview.html#applicationConsiderations">
Application Considerations
</a>
</span>
</dt>
</dl>
</dd>
<dt>
<span class="sect1">
<a href="restore.html">JE Backup and Restore</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="jca.html">JCA Support</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="jmx.html">JConsole and JMX Support</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="gettingit.html">Getting and Using JE </a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="jeexceptions.html">JE Exceptions</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="logfilesrevealed.html">Six Things Everyone Should Know about JE Log Files</a>
</span>
</dt>
</dl>
</div>
<p>
Welcome to Berkeley DB Java Edition (JE). JE is a general-purpose,
transaction-protected, embedded database written in 100% Java (JE
makes no JNI calls). As such, it offers the Java developer safe and
efficient in-process storage and management of arbitrary data.
</p>
<p>
You use JE through a series of Java APIs which give you the
ability to read and write your data, manage your database(s), and
perform other more advanced activities such as managing
transactions. The Java APIs that you use to interact with JE
come in two basic flavors. The first is a high-level API that
allows you to make Java classes persistent. The second is a
lower-level API which provides additional flexibility when interacting
with JE databases.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;">
<h3 class="title">Note</h3>
<p>
For long-time users of JE, the lower-level API is the
traditional API that you are probably accustomed to using.
</p>
</div>
<p>
Regardless of the API set that you choose to use, there are a
series of concepts and APIs that are common across the product.
This manual starts by providing a high-level examination of
JE. It then describes the APIs you use regardless of the API
set that you choose to use. It then provides information on using the
Direct Persistence Layer (DPL) API, followed by information on using
the more extensive "base" API. Finally, we provide some database
administration information.
</p>
<p>
Note that the information provided here is intended to focus on
only introductory API usage. Other books describe more advanced
topics, such as transactional usage. See the <a class="xref" href="moreinfo.html" title="For More Information">For More Information</a> section for
a listing of other titles in the JE documentation set.
</p>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="features"></a>Features</h2>
</div>
</div>
</div>
<div class="toc">
<dl>
<dt>
<span class="sect2">
<a href="introduction.html#dplfeatures">DPL Features</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="introduction.html#basefeatures">Base API Features</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="introduction.html#whichapi">Which API Should You Use?</a>
</span>
</dt>
</dl>
</div>
<p>
JE provides an enterprise-class Java-based data management
solution. All you need to get started is to add a single jar file to your
application's classpath. See <a class="xref" href="gettingit.html" title="Getting and Using JE">Getting and Using JE </a> for more information.
</p>
<p>
JE offers the following major features:
</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>
Large database support. JE databases efficiently scale
from one to millions of records. The size of your JE
databases are likely to be limited more by hardware resources
than by any limits imposed upon you by JE.
</p>
<p>
Databases are described in
<a class="xref" href="databases.html" title="Chapter 7. Databases">Databases</a>.
</p>
</li>
<li>
<p>
Database environments. Database environments provide
a unit of encapsulation and management for one or
more databases. Environments are also the
unit of management for internal resources such as the
in-memory cache and the background threads.
Finally, you use environments to manage concurrency and
transactions. Note that all applications using JE
are required to use database environments.
</p>
<p>
Database environments are described in
<a class="xref" href="env.html" title="Chapter 2. Database Environments">Database Environments</a>.
</p>
</li>
<li>
<p>
Multiple thread and process support. JE is designed for
multiple threads of control. Both read and write operations
can be performed by multiple threads. JE uses record-level
locking for high concurrency in threaded applications.
Further, JE uses timeouts for deadlock detection to help
you ensure that two threads of control do not deadlock
indefinitely.
</p>
<p>
Moreover, JE allows multiple processes to access the same
databases. However, in this configuration JE requires that
there be no more than one process allowed to write to the
database. Read-only processes are guaranteed a consistent,
although potentially out of date, view of the stored data as of
the time that the environment is opened.
</p>
</li>
<li>
<p>Transactions. Transactions allow you to treat one or more
operations on one or more databases as a single unit of work.
JE transactions offer the application developer recoverability, atomicity, and
isolation for your database operations.
</p>
<p>Note that transaction protection is optional. Transactions are
described in the <em class="citetitle">Berkeley DB, Java Edition Getting Started with Transaction Processing</em> guide.</p>
</li>
<li>
<p>
In-memory cache. The cache allows for high speed
database access for both read and write operations by
avoiding unnecessary disk I/O. The cache will grow
on demand up to a pre-configured maximum size. To
improve your application's performance immediately
after startup time, you can preload your cache in
order to avoid disk I/O for production requests of
your data.
</p>
<p>
Cache management is described in
<a class="xref" href="cachesize.html" title="Sizing the Cache">Sizing the Cache</a>.
</p>
</li>
<li>
<p>
Indexes. JE allows you to easily create and maintain
secondary indices for your primary data. In this way, you can obtain rapid
access to your data through the use of an alternative, or
secondary, key.
</p>
<p>
How indices work is dependent upon the API you are
using. If you are using the DPL, see
<a class="xref" href="persist_index.html" title="Chapter 4. Working with Indices">Working with Indices</a>.
Otherwise, see
<a class="xref" href="indexes.html" title="Chapter 10. Secondary Databases">Secondary Databases</a>.
</p>
</li>
<li>
<p>
Log files. JE databases are stored in one
or more numerically-named log files in the environment
directory. The log files are write-once and are
portable across platforms with different endian-ness.
</p>
<p>
Unlike other database implementations, there is no
distinction between database files (that is, the "material
database") and log files. Instead JE employs a log-based storage
system to protect database modifications. Before any
change is made to a database, JE writes information about the
change to the log file.
</p>
<p>
Note that JE's log files are not binary compatible with Berkeley
DB's database files. However, both products provide dump and load
utilities, and the files that these operate on are compatible across
product lines.
</p>
<p>
JE's log files are described in more detail in
<a class="xref" href="backuprestore.html" title="Chapter 11. Backing up and Restoring Berkeley DB Java Edition Applications">Backing up and Restoring Berkeley DB Java Edition Applications</a>.
For information on using JE's dump and load utilities,
see <a class="xref" href="commandlinetools.html" title="The Command Line Tools">The Command Line Tools</a>.
Finally, for a short list of things to know about log files while you are learning JE,
see <a class="xref" href="logfilesrevealed.html" title="Six Things Everyone Should Know about JE Log Files">Six Things Everyone Should Know about JE Log Files</a>.
</p>
</li>
<li>
<p>
Background threads. JE provides several threads
that manage internal resources for you. The
checkpointer is responsible for flushing database
data to disk that was written to cache as the result
of a transaction commit (this is done in order to
shorten recovery time). The compressor thread
removes subtrees from the database that are empty
because of deletion activity. Finally, the cleaner
thread is responsible for cleaning and removing
unneeded log files, thereby helping you to save on
disk space.
</p>
<p>
Background thread management is described in
<a class="xref" href="backgroundthreads.html" title="Managing the Background Threads">Managing the Background Threads</a>.
</p>
</li>
<li>
<p>
Backup and restore. JE's backup procedure
consists of simply copying JE's log files to a
safe location for storage. To recover from a
catastrophic failure, you copy your archived log
files back to your production location on disk and
reopen the JE environment.
</p>
<p>
Note that JE always performs <span class="emphasis"><em>normal
recovery</em></span> when it opens a database
environment. Normal recovery brings the database to a
consistent state based on change information found in
the database log files.
</p>
<p>
JE's backup and recovery mechanisms are described in
<a class="xref" href="backuprestore.html" title="Chapter 11. Backing up and Restoring Berkeley DB Java Edition Applications">Backing up and Restoring Berkeley DB Java Edition Applications</a>.
</p>
</li>
</ul>
</div>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="dplfeatures"></a>DPL Features</h3>
</div>
</div>
</div>
<p>
The DPL is one of two APIs that JE provides for
interaction with JE databases. The DPL provides
the ability to cause any Java type to be persistent
without implementing special interfaces. The
only real requirement is that each persistent
class have a default constructor.
</p>
<p>
The DPL provides all of the features previously identified
in this chapter. In addition, the DPL offers you:
</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>
A type safe, convenient way to access
persistent objects.
</p>
</li>
<li>
<p>
No hand-coding of bindings is required.
A binding is a way of transforming data
types into a format which can be stored
in a JE database. If you do not use
the DPL, you may be required to
create custom bindings for your data
types.
</p>
<p>
See <a class="xref" href="bindAPI.html" title="Using the BIND APIs">Using the BIND APIs</a>
for more information on creating data bindings.
</p>
<p>
Note that Java byte code enhancement is
used by the DPL API to provide fully
optimized bindings that do not use Java
reflection.
</p>
</li>
<li>
<p>
No external schema is required to define
primary and secondary index keys. Java
annotations are used to define all
metadata.
</p>
</li>
<li>
<p>
Interoperability with external components is
supported using the Java collections framework.
Any index can be accessed using a standard
<code class="literal">java.util</code> collection.
</p>
</li>
<li>
<p>
Class evolution is explicitly supported. This
means you can add fields or widen types
automatically and transparently.
</p>
<p>
You can also perform many incompatible class
changes, such as renaming fields or refactoring a
single class. This is done using a built-in
DPL mechanism called
<span class="emphasis"><em>mutations</em></span>.
Mutations are automatically applied as data is
accessed so as to avoid downtime to convert large
databases during a software upgrade.
</p>
</li>
<li>
<p>
Persistent class fields can be private,
package-private, protected or public. The
DPL can access persistence fields
either by bytecode enhancement or by reflection.
</p>
</li>
<li>
<p>
The performance of the underlying JE
engine is safe-guarded. All
DPL operations are mapped directly to
the underlying APIs, object bindings are
lightweight, and all engine tuning parameters are
available.
</p>
</li>
<li>
<p>
Java 1.5 generic types and annotations are
supported.
</p>
</li>
</ul>
</div>
</div>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="basefeatures"></a>Base API Features</h3>
</div>
</div>
</div>
<p>
If you are not using the DPL, then the following concepts and
features are likely to be of interest to you:
</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>
Database records. All database records are organized
as simple key/data pairs. Both keys and data can be
anything from primitive Java types to the most
complex of Java objects.
</p>
<p>
Database records are described in
<a class="xref" href="DBEntry.html" title="Chapter 8. Database Records">Database Records</a>.
</p>
</li>
<li>
<p>
Direct database read and write. You can use methods
of a <code class="classname">Database</code> object to read
and write database records. Reading and writing using
<code class="classname">Database</code> objects are described
in
<a class="xref" href="DBEntry.html" title="Chapter 8. Database Records">Database Records</a>.
</p>
</li>
<li>
<p>
Cursors. Cursors give you the ability to sequentially
move through a database. Using cursors, you can seek
to a specific point in the database (using search
criteria applied to the key and/or the data portion
of a database record) and then either step forward or
step backwards through the database.
</p>
<p>
Cursors are described in detail in
<a class="xref" href="Cursors.html" title="Chapter 9. Using Cursors">Using Cursors</a>.
</p>
</li>
<li>
<p>
JCA. JE provides support for the Java Connector Architecture. See
<a class="xref" href="jca.html" title="JCA Support">JCA Support</a> for more information.
</p>
</li>
<li>
<p>
JMX. JE provides support for Java Management Extensions.
See <a class="xref" href="jmx.html" title="JConsole and JMX Support">JConsole and JMX Support</a> for more information.
</p>
</li>
</ul>
</div>
</div>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="whichapi"></a>Which API Should You Use?</h3>
</div>
</div>
</div>
<p>
Of the two APIs that JE makes available to you, we
recommend that you use the DPL if all
you want to do is make classes with a relatively static schema to
be persistent.
</p>
<p>
Further, if you are porting an application between Berkley DB
and Berkeley DB Java Edition, then you should not use the DPL as the
base API is a much closer match to the Berkley DB Java API.
</p>
<p>
Additionally, if your application uses a highly dynamic
schema, then the DPL is probably a poor choice for
your application, although the use of Java annotations
can make the DPL work a little better for you in this
situation.
</p>
</div>
</div>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="moreinfo.html">Prev</a> </td>
<td width="20%" align="center"> </td>
<td width="40%" align="right"> <a accesskey="n" href="applicationoverview.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">For More Information </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> The JE Application</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,148 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Inventory.java</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="dpl_example.html" title="Chapter 6. A DPL Example" />
<link rel="prev" href="dpl_example.html" title="Chapter 6. A DPL Example" />
<link rel="next" href="mydbenv-persist.html" title="MyDbEnv" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Inventory.java</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="dpl_example.html">Prev</a> </td>
<th width="60%" align="center">Chapter 6. A DPL Example</th>
<td width="20%" align="right"> <a accesskey="n" href="mydbenv-persist.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="inventoryclass"></a>Inventory.java</h2>
</div>
</div>
</div>
<p>
Our example's <code class="classname">Inventory</code>
class is much like our <code class="classname">Vendor</code>
class in that it is simply used to encapsulate
data. However, in this case we want to be able
to access objects two different ways: by
product SKU and by product name.
</p>
<p>
In our data set, the product SKU is required to be
unique, so we use that as the primary key. The
product name, however, is not a unique value so we
set this up as a secondary key.
</p>
<p>
The class appears as follows in our example:
</p>
<pre class="programlisting">package persist.gettingStarted;
import com.sleepycat.persist.model.Entity;
import com.sleepycat.persist.model.PrimaryKey;
import static com.sleepycat.persist.model.Relationship.*;
import com.sleepycat.persist.model.SecondaryKey;
@Entity
public class Inventory {
// Primary key is sku
@PrimaryKey
private String sku;
// Secondary key is the itemName
@SecondaryKey(relate=MANY_TO_ONE)
private String itemName;
private String category;
private String vendor;
private int vendorInventory;
private float vendorPrice;
public void setSku(String data) {
sku = data;
}
public void setItemName(String data) {
itemName = data;
}
public void setCategory(String data) {
category = data;
}
public void setVendorInventory(int data) {
vendorInventory = data;
}
public void setVendor(String data) {
vendor = data;
}
public void setVendorPrice(float data) {
vendorPrice = data;
}
public String getSku() {
return sku;
}
public String getItemName() {
return itemName;
}
public String getCategory() {
return category;
}
public int getVendorInventory() {
return vendorInventory;
}
public String getVendor() {
return vendor;
}
public float getVendorPrice() {
return vendorPrice;
}
} </pre>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="dpl_example.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="dpl_example.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="mydbenv-persist.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Chapter 6. A DPL Example </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> MyDbEnv</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,106 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>JCA Support</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="introduction.html" title="Chapter 1. Introduction to Berkeley DB Java Edition" />
<link rel="prev" href="restore.html" title="JE Backup and Restore" />
<link rel="next" href="jmx.html" title="JConsole and JMX Support" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">JCA Support</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="restore.html">Prev</a> </td>
<th width="60%" align="center">Chapter 1. Introduction to Berkeley DB Java Edition </th>
<td width="20%" align="right"> <a accesskey="n" href="jmx.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="jca"></a>JCA Support</h2>
</div>
</div>
</div>
<p>
<span class="emphasis"><em>JCA</em></span> is the <span class="emphasis"><em>Java Connector Architecture</em></span>. This architecture provides a standard for connecting
the J2EE platform to legacy enterprise information systems (EIS), such as ERP systems, database systems, and
legacy applications not written in Java. JE supports this architecture.
</p>
<p>
Users who want to run JE within a J2EE Application Server can use the JCA Resource Adapter to connect to
JE through a standard API. Note that the base API is required if you want to do this.
The JE Resource Adapter supports all three J2EE application server transaction
types:
</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>
No transaction.
</p>
</li>
<li>
<p>
Local transactions.
</p>
</li>
<li>
<p>
XA transactions.
</p>
</li>
</ul>
</div>
<p>
JCA also includes the Java Transaction API (JTA), which means that JE supports 2 phase commit (XA).
Therefore, JEs can participate in distributed transactions managed by either a J2EE server or the
applications direct use of the JTA API.
</p>
<p>
The JE distribution includes an example showing JCA usage in a simple EJB. The Resource Adaptor has been
tested using JBoss 3.2.6, and the Sun Java System Application Server, version 8.1. Instructions for how to build
the Resource Adapter and run a simple "smoke test" example for each of the application servers can be found
here:
</p>
<pre class="programlisting"><span class="emphasis"><em>JE_HOME</em></span>/examples/jca/HOWTO-jboss.txt</pre>
<p>
and
</p>
<pre class="programlisting"><span class="emphasis"><em>JE_HOME</em></span>/examples/jca/HOWTO-sjsas.txt</pre>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="restore.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="introduction.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="jmx.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">JE Backup and Restore </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> JConsole and JMX Support</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,154 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>JE Exceptions</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="introduction.html" title="Chapter 1. Introduction to Berkeley DB Java Edition" />
<link rel="prev" href="gettingit.html" title="Getting and Using JE" />
<link rel="next" href="logfilesrevealed.html" title="Six Things Everyone Should Know about JE Log Files" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">JE Exceptions</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="gettingit.html">Prev</a> </td>
<th width="60%" align="center">Chapter 1. Introduction to Berkeley DB Java Edition </th>
<td width="20%" align="right"> <a accesskey="n" href="logfilesrevealed.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="jeexceptions"></a>JE Exceptions</h2>
</div>
</div>
</div>
<p>
Before describing the Java API usage, it is first useful to examine the
exceptions thrown by those APIs. So, briefly, this section describes the
exceptions that you can generally expect to encounter when writing JE
applications. This list is not definitive. Exceptions beyond these can be
expected, depending on the specific database activity you are performing.
See the Javadoc for more information.
</p>
<p>
All of the JE APIs throw
<code class="classname">DatabaseException</code>.
<a class="ulink" href="../java/com/sleepycat/je/DatabaseException.html" target="_top">DatabaseException</a> extends
<code class="classname">java.lang.Exception</code>. Also, the following
classes are subclasses of <code class="classname">DatabaseException</code>:
</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>
<a class="ulink" href="../java/com/sleepycat/je/DatabaseNotFoundException.html" target="_top">DatabaseNotFoundException</a>
</p>
<p>
Thrown whenever an operation requires a database, and that
database cannot be found.
</p>
</li>
<li>
<p>
<a class="ulink" href="../java/com/sleepycat/je/DiskLimitException.html" target="_top">DiskLimitException</a>
</p>
<p>
Indicates that you have reached your disk usage thresholds. Writes are
no longer allowed when these thresholds are exceeded. The thresholds
are set using the <a class="ulink" href="../java/com/sleepycat/je/EnvironmentConfig.html#MAX_DISK" target="_top">EnvironmentConfig.MAX_DISK</a> and <a class="ulink" href="../java/com/sleepycat/je/EnvironmentConfig.html#FREE_DISK" target="_top">EnvironmentConfig.FREE_DISK</a> properties. This exception
can be thrown as the result of any write operation, including database
record writes, checkpoints, and database and environment syncs.
</p>
<p>
When closing the environment, this exception can be seen.
However, the environment will still be properly closed.
</p>
<p>
For information on setting these properties, see
<a class="xref" href="diskthreshold.html" title="Setting Disk Thresholds">Setting Disk Thresholds</a>.
</p>
</li>
<li>
<p>
<a class="ulink" href="../java/com/sleepycat/je/EnvironmentFailureException.html" target="_top">EnvironmentFailureException</a>
</p>
<p>
Indicates that a failure has occurred that could impact the Environment as
a whole. Depending on the nature of the failure, this exception might
indicate that <a class="ulink" href="../java/com/sleepycat/je/Environment.html#close--" target="_top">Environment.close()</a> should
be called. Use <a class="ulink" href="../java/com/sleepycat/je/Environment.html#isValid--" target="_top">Environment.isValid()</a> to
determine if all <a class="ulink" href="../java/com/sleepycat/je/Environment.html" target="_top">Environment</a> handles must
be reopened. If <code class="literal">true</code>, the environment can
continue operating without being reopened.
</p>
</li>
<li>
<p>
<a class="ulink" href="../java/com/sleepycat/je/LockConflictException.html" target="_top">LockConflictException</a>
</p>
<p>
The common base class for all exceptions that result from record
lock conflicts. Upon receiving this exception, any open cursors
must be closed, the enclosing transaction aborted and,
optionally, the transaction retried. Transactions are described
in the <em class="citetitle">Berkeley DB, Java Edition Getting Started with Transaction Processing</em> guide.
</p>
</li>
<li>
<p>
<a class="ulink" href="../java/com/sleepycat/je/LogWriteException.html" target="_top">LogWriteException</a>
</p>
<p>
Thrown when an <code class="classname">IOException</code> or other failure occurs
when writing to the JE log. This exception might be indicative of a
full disk, although an <code class="classname">IOException</code> does not contain
enough information to determine this definitively.
</p>
<p>
This exception can be thrown as the result of any write
operation, including database record writes, checkpoints, and
database and environment syncs.
</p>
</li>
</ul>
</div>
<p>
Note that <code class="classname">DatabaseException</code> and its subclasses belong to the
<code class="literal">com.sleepycat.je</code> package.
</p>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="gettingit.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="introduction.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="logfilesrevealed.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Getting and Using JE  </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Six Things Everyone Should Know about JE Log Files</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,74 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>JConsole and JMX Support</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="introduction.html" title="Chapter 1. Introduction to Berkeley DB Java Edition" />
<link rel="prev" href="jca.html" title="JCA Support" />
<link rel="next" href="gettingit.html" title="Getting and Using JE" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">JConsole and JMX Support</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="jca.html">Prev</a> </td>
<th width="60%" align="center">Chapter 1. Introduction to Berkeley DB Java Edition </th>
<td width="20%" align="right"> <a accesskey="n" href="gettingit.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="jmx"></a>JConsole and JMX Support</h2>
</div>
</div>
</div>
<p>
<span class="emphasis"><em>JMX</em></span> is the <span class="emphasis"><em>Java Management Extensions</em></span>. This extension provides
tools for managing and monitoring devices, applications, and service-driven networks. JE supports this extension.
</p>
<p>
The JE distribution supplies MBeans that can be deployed for monitoring a JE environment in any JMX
server (such as an J2EE application server). Statistics and key operations can be invoked from these MBeans.
In addition, JE provides a plugin for the <span class="emphasis"><em>jconsole</em></span> utility which
lets the user graphically access this information.
</p>
<p>
For information on how to use the <span class="emphasis"><em>jconsole</em></span> plugin see:
</p>
<pre class="programlisting"><span class="emphasis"><em>JE_HOME</em></span>/docs/jconsole/JConsole-plugin.html</pre>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="jca.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="introduction.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="gettingit.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">JCA Support </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Getting and Using JE </td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,377 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Database Joins</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="indexes.html" title="Chapter 10. Secondary Databases" />
<link rel="prev" href="secondaryCursor.html" title="Using Secondary Cursors" />
<link rel="next" href="indexusage.html" title="Secondary Database Example" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Database Joins</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="secondaryCursor.html">Prev</a> </td>
<th width="60%" align="center">Chapter 10. Secondary Databases</th>
<td width="20%" align="right"> <a accesskey="n" href="indexusage.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="joins"></a>Database Joins</h2>
</div>
</div>
</div>
<div class="toc">
<dl>
<dt>
<span class="sect2">
<a href="joins.html#joinUsage">Using Join Cursors</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="joins.html#joinconfig">JoinCursor Properties</a>
</span>
</dt>
</dl>
</div>
<p>
If you have two or more secondary databases associated with a primary
database, then you can retrieve primary records based on the intersection of
multiple secondary entries. You do this using a
<span><code class="classname">JoinCursor</code>.</span>
</p>
<p>
Throughout this document we have presented a
<span>class</span>
that stores
<span>inventory</span>
information on grocery
<span>items.</span>
That
<span>class</span>
is fairly simple with a limited
number of data members, few of which would be interesting from a query
perspective. But suppose, instead, that we were storing
information on something with many more characteristics that can be queried, such
as an automobile. In that case, you may be storing information such as
color, number of doors, fuel mileage, automobile type, number of
passengers, make, model, and year, to name just a few.
</p>
<p>
In this case, you would still likely be using some unique value to key your
primary entries (in the United States, the automobile's VIN would be
ideal for this purpose). You would then create a
<span>class</span>
that identifies
all the characteristics of the automobiles in your inventory.
<span>
You would
also have to create some mechanism by which you would move instances of
this class in and out of Java <code class="literal">byte</code> arrays. We
described the concepts and mechanisms by which you can perform these
activities in <a class="xref" href="DBEntry.html" title="Chapter 8. Database Records">Database Records</a>.
</span>
</p>
<p>
To query this data, you might then create multiple secondary databases,
one for each of the characteristics that you want to query. For
example, you might create a secondary for color, another for number of
doors, another for number of passengers, and so forth. Of course, you
will need a unique
<span>key creator</span>
for each such secondary database. You do
all of this using the concepts and techniques described throughout this
chapter.
</p>
<p>
Once you have created this primary database and all interesting
secondaries, what you have is the ability to retrieve automobile records
based on a single characteristic. You can, for example, find all the
automobiles that are red. Or you can find all the automobiles that have
four doors. Or all the automobiles that are minivans.
</p>
<p>
The next most natural step, then, is to form compound queries, or joins.
For example, you might want to find all the automobiles that are red,
and that were built by Toyota, and that are minivans. You can do this
using a
<span><code class="classname">JoinCursor</code> class instance.</span>
</p>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="joinUsage"></a>Using Join Cursors</h3>
</div>
</div>
</div>
<p>
To use a join cursor:
</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>
Open two or more
<span>secondary cursors. These </span>
cursors
<span>must be obtained from</span>
secondary databases that are associated with
the same primary database.
</p>
</li>
<li>
<p>
Position each such cursor to the secondary key
value in which you are interested. For example, to build on
the previous description, the cursor for the color
database is positioned to the <code class="literal">red</code> records
while the cursor for the model database is positioned to the
<code class="literal">minivan</code> records, and the cursor for the
make database is positioned to <code class="literal">Toyota</code>.
</p>
</li>
<li>
<p>
Create an array of <span>secondary</span> cursors, and
place in it each of the cursors that are participating in your join query.
</p>
</li>
<li>
<p>
Obtain a join cursor. You do this using the
<code class="methodname">Database.join()</code>
method. You must pass this method the array of secondary cursors that you
opened and positioned in the previous steps.
</p>
</li>
<li>
<p>
Iterate over the set of matching records
<span>using <code class="methodname">JoinCursor.getNext()</code></span>
until
<span><code class="classname">OperationStatus</code> is not <code class="literal">SUCCESS</code>.</span>
</p>
</li>
<li>
<p>
Close your <span>join</span> cursor.
</p>
</li>
<li>
<p>
If you are done with them, close all your <span>secondary</span> cursors.
</p>
</li>
</ul>
</div>
<p>
For example:
</p>
<a id="je_index9"></a>
<pre class="programlisting">package je.gettingStarted;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.JoinCursor;
import com.sleepycat.je.LockMode;
import com.sleepycat.je.OperationStatus;
import com.sleepycat.je.SecondaryCursor;
import com.sleepycat.je.SecondaryDatabase;
...
// Database and secondary database opens omitted for brevity.
// Assume a primary database handle:
// automotiveDB
// Assume 3 secondary database handles:
// automotiveColorDB -- index based on automobile color
// automotiveTypeDB -- index based on automobile type
// automotiveMakeDB -- index based on the manufacturer
// Query strings:
String theColor = "red";
String theType = "minivan";
String theMake = "Toyota";
// Secondary cursors used for the query:
SecondaryCursor colorSecCursor = null;
SecondaryCursor typeSecCursor = null;
SecondaryCursor makeSecCursor = null;
// The join cursor
JoinCursor joinCursor = null;
// These are needed for our queries
DatabaseEntry foundKey = new DatabaseEntry();
DatabaseEntry foundData = new DatabaseEntry();
// All cursor operations are enclosed in a try block to ensure that they
// get closed in the event of an exception.
try {
// Database entries used for the query:
DatabaseEntry color = new DatabaseEntry(theColor.getBytes("UTF-8"));
DatabaseEntry type = new DatabaseEntry(theType.getBytes("UTF-8"));
DatabaseEntry make = new DatabaseEntry(theMake.getBytes("UTF-8"));
colorSecCursor = automotiveColorDB.openSecondaryCursor(null, null);
typeSecCursor = automotiveTypeDB.openSecondaryCursor(null, null);
makeSecCursor = automotiveMakeDB.openSecondaryCursor(null, null);
// Position all our secondary cursors to our query values.
OperationStatus colorRet =
colorSecCursor.getSearchKey(color, foundData, LockMode.DEFAULT);
OperationStatus typeRet =
typeSecCursor.getSearchKey(type, foundData, LockMode.DEFAULT);
OperationStatus makeRet =
makeSecCursor.getSearchKey(make, foundData, LockMode.DEFAULT);
// If all our searches returned successfully, we can proceed
if (colorRet == OperationStatus.SUCCESS &amp;&amp;
typeRet == OperationStatus.SUCCESS &amp;&amp;
makeRet == OperationStatus.SUCCESS) {
// Get a secondary cursor array and populate it with our
// positioned cursors
SecondaryCursor[] cursorArray = {colorSecCursor,
typeSecCursor,
makeSecCursor};
// Create the join cursor
joinCursor = automotiveDB.join(cursorArray, null);
// Now iterate over the results, handling each in turn
while (joinCursor.getNext(foundKey, foundData, LockMode.DEFAULT) ==
OperationStatus.SUCCESS) {
// Do something with the key and data retrieved in
// foundKey and foundData
}
}
} catch (DatabaseException dbe) {
// Error reporting goes here
} catch (Exception e) {
// Error reporting goes here
} finally {
try {
// Make sure to close out all our cursors
if (colorSecCursor != null) {
colorSecCursor.close();
}
if (typeSecCursor != null) {
typeSecCursor.close();
}
if (makeSecCursor != null) {
makeSecCursor.close();
}
if (joinCursor != null) {
joinCursor.close();
}
} catch (DatabaseException dbe) {
// Error reporting goes here
}
} </pre>
</div>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="joinconfig"></a>JoinCursor Properties</h3>
</div>
</div>
</div>
<p>
You can set <code class="classname">JoinCursor</code> properties using the
<code class="classname">JoinConfig</code> class. Currently there is just one property that you can
set:
</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>
<code class="methodname">JoinConfig.setNoSort()</code>
</p>
<p>
Specifies whether automatic sorting of input cursors is disabled. The cursors are sorted from the
one that refers to the least number of data items to the one that refers to the most.
</p>
<p>
If the data is structured so that cursors with many data items also share many common elements,
higher performance will result from listing those cursors before cursors with fewer data
items. Turning off sorting permits applications to specify cursors in the proper order given this
scenario.
</p>
<p>
The default value is <code class="literal">false</code> (automatic cursor sorting is performed).
</p>
<p>
For example:
</p>
<a id="je_index10"></a>
<pre class="programlisting">// All database and environments omitted
JoinConfig config = new JoinConfig();
config.setNoSort(true);
JoinCursor joinCursor = myDb.join(cursorArray, config); </pre>
</li>
</ul>
</div>
</div>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="secondaryCursor.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="indexes.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="indexusage.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">
<span>Using Secondary Cursors</span>
 </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Secondary Database Example</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,241 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Implementing Key Creators</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="indexes.html" title="Chapter 10. Secondary Databases" />
<link rel="prev" href="indexes.html" title="Chapter 10. Secondary Databases" />
<link rel="next" href="secondaryProps.html" title="Secondary Database Properties" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Implementing Key
<span xmlns="http://www.w3.org/1999/xhtml">Creators</span>
</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="indexes.html">Prev</a> </td>
<th width="60%" align="center">Chapter 10. Secondary Databases</th>
<td width="20%" align="right"> <a accesskey="n" href="secondaryProps.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="keyCreator"></a>Implementing Key
<span>Creators</span>
</h2>
</div>
</div>
</div>
<p>
You must provide every secondary database with a
<span>class</span>
that creates keys from primary records. You identify this
<span>class</span>
<span>
using the <code class="methodname">SecondaryConfig.setKeyCreator()</code>
method.
</span>
</p>
<p>
You can create keys using whatever data you want. Typically you will
base your key on some information found in a record's data, but you
can also use information found in the primary record's key. How you build
your keys is entirely dependent upon the nature of the index that you
want to maintain.
</p>
<p>
You implement a key creator by writing a class that implements the
<code class="classname">SecondaryKeyCreator</code> interface. This interface
requires you to implement the <code class="methodname">SecondaryKeyCreator.createSecondaryKey()</code>
method.
</p>
<p>
One thing to remember when implementing this method is that you will
need a way to extract the necessary information from the data's
<code class="classname">DatabaseEntry</code> and/or the key's
<code class="classname">DatabaseEntry</code> that are provided on calls to this
method. If you are using complex objects, then you are probably using the
Bind APIs to perform this conversion. The easiest thing to do is to
instantiate the <code class="classname">EntryBinding</code> or
<code class="classname">TupleBinding</code> that you need to perform the
conversion, and then provide this to your key creator's constructor.
The Bind APIs are introduced in <a class="xref" href="bindAPI.html" title="Using the BIND APIs">Using the BIND APIs</a>.
</p>
<p>
<code class="methodname">SecondaryKeyCreator.createSecondaryKey()</code> returns a
boolean. A return value of <code class="literal">false</code> indicates that
no secondary key exists, and therefore no record should be added to the secondary database for that primary record.
If a record already exists in the secondary database, it is deleted.
</p>
<p>
For example, suppose your primary database uses the following class
for its record data:
</p>
<a id="je_index3"></a>
<pre class="programlisting">package je.gettingStarted;
public class PersonData {
private String userID;
private String surname;
private String familiarName;
public PersonData(String userID, String surname,
String familiarName) {
this.userID = userID;
this.surname = surname;
this.familiarName = familiarName;
}
public String getUserID() {
return userID;
}
public String getSurname() {
return surname;
}
public String getFamiliarName() {
return familiarName;
}
} </pre>
<p>
Also, suppose that you have created a custom tuple binding,
<code class="classname">PersonDataBinding</code>, that you use to convert
<code class="classname">PersonData</code> objects to and from
<code class="classname">DatabaseEntry</code> objects. (Custom tuple bindings are
described in <a class="xref" href="bindAPI.html#customTuple" title="Custom Tuple Bindings">Custom Tuple Bindings</a>.)
</p>
<p>
Finally, suppose you want a secondary database that is keyed based
on the person's full name.
</p>
<p>
Then in this case you might create a key creator as follows:
</p>
<a id="je_index4"></a>
<pre class="programlisting">package je.gettingStarted;
import com.sleepycat.bind.tuple.TupleBinding;
import com.sleepycat.je.SecondaryKeyCreator;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.SecondaryDatabase;
import java.io.IOException;
public class FullNameKeyCreator implements SecondaryKeyCreator {
private TupleBinding theBinding;
public FullNameKeyCreator(TupleBinding theBinding1) {
theBinding = theBinding1;
}
public boolean createSecondaryKey(SecondaryDatabase secDb,
DatabaseEntry keyEntry,
DatabaseEntry dataEntry,
DatabaseEntry resultEntry) {
try {
PersonData pd =
(PersonData) theBinding.entryToObject(dataEntry);
String fullName = pd.getFamiliarName() + " " +
pd.getSurname();
resultEntry.setData(fullName.getBytes("UTF-8"));
} catch (IOException willNeverOccur) {}
return true;
}
} </pre>
<p>Finally, you use this key creator as follows:</p>
<a id="je_index5"></a>
<pre class="programlisting">package je.gettingStarted;
import com.sleepycat.bind.tuple.TupleBinding;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Environment;
import com.sleepycat.je.SecondaryDatabase;
import com.sleepycat.je.SecondaryConfig;
...
Environment myEnv = null;
Database myDb = null;
SecondaryDatabase mySecDb = null;
try {
// Environment and primary database open omitted for brevity
...
TupleBinding myDataBinding = new MyTupleBinding();
FullNameKeyCreator fnkc = new FullNameKeyCreator(myDataBinding);
SecondaryConfig mySecConfig = new SecondaryConfig();
mySecConfig.setKeyCreator(fnkc);
//Perform the actual open
String secDbName = "mySecondaryDatabase";
mySecDb = myEnv.openSecondaryDatabase(null, secDbName, myDb,
mySecConfig);
} catch (DatabaseException de) {
// Exception handling goes here
} finally {
try {
if (mySecDb != null) {
mySecDb.close();
}
if (myDb != null) {
myDb.close();
}
if (myEnv != null) {
myEnv.close();
}
} catch (DatabaseException dbe) {
// Exception handling goes here
}
}</pre>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="indexes.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="indexes.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="secondaryProps.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Chapter 10. Secondary Databases </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Secondary Database Properties</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,133 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Six Things Everyone Should Know about JE Log Files</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="introduction.html" title="Chapter 1. Introduction to Berkeley DB Java Edition" />
<link rel="prev" href="jeexceptions.html" title="JE Exceptions" />
<link rel="next" href="env.html" title="Chapter 2. Database Environments" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Six Things Everyone Should Know about JE Log Files</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="jeexceptions.html">Prev</a> </td>
<th width="60%" align="center">Chapter 1. Introduction to Berkeley DB Java Edition </th>
<td width="20%" align="right"> <a accesskey="n" href="env.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="logfilesrevealed"></a>Six Things Everyone Should Know about JE Log Files</h2>
</div>
</div>
</div>
<p>
JE log files are not like the log files of other database systems. Nor are they like the log files or database
files created by Berkeley DB C Edition. In this guide you will learn more about log files as you go along, but it is good
to keep the following points in mind as you begin using JE.
</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>
JE log files are "append only". Record insertions, deletions, and updates are always added at the end
of the current file. The first file is named <code class="literal">00000000.jdb</code>. When that file grows to a certain size
(10 MB by default) a new file named <code class="literal">00000001.jdb</code> becomes the current file, and so on.
</p>
</li>
<li>
<p>
There are no separate database files. Unlike Berkeley DB C Edition, databases are not stored in files
that are separate from the transaction log. The transaction log and the database records are stored
together in a single sequential log consisting of multiple log files.
</p>
</li>
<li>
<p>
The JE cleaner is responsible for reclaiming unused disk space. When the records in a log file are
superseded by deletions or updates recorded in a later log file, the older log file is no longer fully
utilized. The cleaner, which operates by default as a separate thread, determines the least utilized
log files, copies any still utilized records in those files to the end of the current log file, and
finally deletes the now completely un-utilized log file.
</p>
<p>
See <a class="xref" href="backgroundthreads.html#cleaner" title="The Cleaner Thread">The Cleaner Thread</a> for more information on the cleaner.
</p>
</li>
<li>
<p>
Cleaning does not start immediately and never produces 100% utilization. Until you have written enough
data to create several log files, and some of that data is obsoleted through deletions and updates, you
will not notice any log files being deleted by the cleaner. By default cleaning occurs in the background and
maintains the log files at 50% utilization. You can configure a higher utilization value, but
configuring too high a utilization value will reduce overall performance.
</p>
</li>
<li>
<p>
Cleaning is not automatically performed when closing the environment. If you wish to reduce unused disk
space to a minimum at a particular point in time, you must explicitly call a method to perform log
cleaning. See the <a class="xref" href="envclose.html" title="Closing Database Environments">Closing Database Environments</a> for more information.
</p>
</li>
<li>
<p>
Log file deletion only occurs after a checkpoint. The cleaner prepares log files to be deleted, but
file deletion must be performed after a checkpoint to ensure that the files are no longer referenced.
Checkpoints occur on their own schedule, which is every 20 MB of log written, by default. This is part
of the reason that you will not see log files being deleted until after several files have been created.
</p>
<p>
When using JE's replication (high availability) feature, a checkpoint does not delete
the cleaned log file but instead instead changes the status of the file to <span class="emphasis"><em>reserved</em></span>.
Reserved files are only deleted when disk utilization exceeds the values set for either
<a class="ulink" href="../java/com/sleepycat/je/EnvironmentConfig.html#MAX_DISK" target="_top">EnvironmentConfig.MAX_DISK</a> or <a class="ulink" href="../java/com/sleepycat/je/EnvironmentConfig.html#FREE_DISK" target="_top">EnvironmentConfig.FREE_DISK</a>.
</p>
</li>
<li>
<p>
Log files can be spread across multiple directories, and therefore across multiple
disks through the use of links or mount points. See
<a class="xref" href="env.html#multisubdir" title="Multiple Environment Subdirectories">Multiple Environment Subdirectories</a>
for more information.
</p>
</li>
</ol>
</div>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="jeexceptions.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="introduction.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="env.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">JE Exceptions </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Chapter 2. Database Environments</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,260 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Logging</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="administration.html" title="Chapter 12. Administering Berkeley DB Java Edition Applications" />
<link rel="prev" href="commandlinetools.html" title="The Command Line Tools" />
<link rel="next" href="concurrentProcessing.html" title="Appendix A. Concurrent Processing in Berkeley DB Java Edition" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Logging</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="commandlinetools.html">Prev</a> </td>
<th width="60%" align="center">Chapter 12. Administering Berkeley DB Java Edition Applications</th>
<td width="20%" align="right"> <a accesskey="n" href="concurrentProcessing.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="managelogging"></a>Logging</h2>
</div>
</div>
</div>
<div class="toc">
<dl>
<dt>
<span class="sect2">
<a href="managelogging.html#logginglevels">Managing Logging Levels</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="managelogging.html#handlerlevels">Managing Handler Levels</a>
</span>
</dt>
</dl>
</div>
<p>
JE uses the <a class="ulink" href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/logging/package-summary.html" target="_top">java.util.logging</a> package to
log operations and trace messages. A distinct logger is defined for
each significant component of the system. The use of distinct loggers, along with
controllable logging levels, allows the logging output to be
tuned to tell you exactly what you need to know (while avoiding a lot of
extra information that only gets in the way) in order to monitor
your application's activities and/or debug runtime problems.
</p>
<p>
Logging output can be displayed to the console and the
<code class="filename">je.info</code> file in your application's
environment directory. Setting the logger level controls the
types of messages that are published to the handlers. Setting the handler level
determines if and where the published messages are displayed.
</p>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="logginglevels"></a>Managing Logging Levels</h3>
</div>
</div>
</div>
<p>
The default logging level for JE loggers is
<code class="literal">INFO</code>. At that level, a non-replicated
environment issues messages only when critical exceptions are
encountered. A replicated environment issues node transition
messages which should be comprehensible to the user familiar with
the replication group life cycle and can be extremely useful when
monitoring your application's activities. The output at the
<code class="literal">INFO</code> is not verbose; it simply details the
node start up and shutdown operations. Initial configuration
problems, if any, should show up during the startup operation.
You are strongly advised to run your production application with
this level of logging.
</p>
<p>
Finer levels of logging are available for debugging purposes.
These will generate verbose output that is rich in implementation
detail. The output at these levels is only likely to be helpful
to people familiar with JE's implementation and the
application's use of JE, so you should only configure your logging
for these more verbose levels if you are involved in a detailed
debugging effort.
</p>
<p>
To set or change the logger level <span class="emphasis"><em>before</em></span> the environment is
opened, do one of the following:
</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>
Set logging levels using the standard Java <a class="ulink" href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/logging/LogManager.html" target="_top">LogManager</a>
properties file. For example, you can set:
</p>
<pre class="programlisting">com.sleepycat.je.level=INFO</pre>
<p>
in the <a class="ulink" href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/logging/LogManager.html" target="_top">LogManager</a> properties file to set the logger
level for all JE loggers.
</p>
</li>
<li>
<p>
Set logging levels programmatically using the
<a class="ulink" href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/logging/package-summary.html" target="_top">java.util.logging</a> API. For example:
</p>
<pre class="programlisting">...
// All other imports are omitted for brevity
import java.util.logging.Logger;
...
Logger parent = Logger.getLogger("com.sleepycat.je");
parent.setLevel(Level.FINE); // Loggers will now publish more
// detailed messages. </pre>
</li>
</ol>
</div>
<p>
To set or change the logger level <span class="emphasis"><em>after</em></span> the environment is
opened, do one of the following:
</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>
Use the standard java.util.logging MBean to set a
concrete JE logger.
</p>
</li>
<li>
<p>
Use the JEDiagnostic MBean to set the parent
<code class="literal">com.sleepycat.je</code> logger.
See the <a class="ulink" href="..//jconsole/JConsole-plugin.html" target="_top">JConsole Plugin</a> page for information on
this MBean.
</p>
</li>
<li>
<p>
Use the programmatic <a class="ulink" href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/logging/package-summary.html" target="_top">java.util.logging</a> API described
above to change the logger.
</p>
</li>
</ol>
</div>
</div>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="handlerlevels"></a>Managing Handler Levels</h3>
</div>
</div>
</div>
<p>
Output to the <code class="filename">je.info</code> file is managed by
the JE <a class="ulink" href="../java/com/sleepycat/je/util/FileHandler.html" target="_top">FileHandler</a>, while output to the console is managed
by the JE <a class="ulink" href="../java/com/sleepycat/je/util/ConsoleHandler.html" target="_top">ConsoleHandler</a>. By default, no output is shown on
the console, and only <code class="literal">INFO</code> level messages are
sent to <code class="filename">je.info</code>.
</p>
<p>
To set or change the handler level <span class="emphasis"><em>before</em></span> the environment is
opened, do one of the following:
</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>
Set logging levels using the standard Java
<a class="ulink" href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/logging/LogManager.html" target="_top">LogManager</a> properties file. For example, you can
set:
</p>
<pre class="programlisting">com.sleepycat.je.util.FileHandler.level=ALL
com.sleepycat.je.util.ConsoleHandler.level=ALL</pre>
<p>
in the <a class="ulink" href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/logging/LogManager.html" target="_top">LogManager</a> properties file to display all
logging output to the console and
<code class="filename">je.info</code> files.
</p>
</li>
<li>
<p>
The <a class="ulink" href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/logging/package-summary.html" target="_top">java.util.logging</a> package does not supply an
API for setting handler levels. Instead, use the
following JE environment parameter:
</p>
<pre class="programlisting">...
EnvironmentConfig envConfig = new EnvironmentConfig();
envConfig.setAllowCreate(true);
envConfig.setConfigParam(EnvironmentConfig.FILE_LOGGING_LEVEL, "ALL");
envConfig.setConfigParam(EnvironmentConfig.CONSOLE_LOGGING_LEVEL,
"ALL");
...
// Open your environment as normal here
... </pre>
</li>
</ol>
</div>
<p>
To set or change the handler level <span class="emphasis"><em>after</em></span> the environment is
opened, do one of the following:
</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>
Use <a class="ulink" href="../java/com/sleepycat/je/EnvironmentMutableConfig.html#setConfigParam(java.lang.String, java.lang.String)" target="_top">EnvironmentMutableConfig.setConfigParam()</a> to change the
handler levels using the JE properties described
above.
</p>
</li>
<li>
<p>
Use the JEDiagnostic MBean to change handler levels.
See the <a class="ulink" href="..//jconsole/JConsole-plugin.html" target="_top">JConsole Plugin</a> page for information on
this MBean.
</p>
</li>
</ol>
</div>
</div>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="commandlinetools.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="administration.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="concurrentProcessing.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">The Command Line Tools </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Appendix A. Concurrent Processing in Berkeley DB Java Edition</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,165 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>For More Information</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="preface.html" title="Preface" />
<link rel="prev" href="preface.html" title="Preface" />
<link rel="next" href="introduction.html" title="Chapter 1. Introduction to Berkeley DB Java Edition" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">For More Information</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="preface.html">Prev</a> </td>
<th width="60%" align="center">Preface</th>
<td width="20%" align="right"> <a accesskey="n" href="introduction.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="moreinfo"></a>For More Information</h2>
</div>
</div>
</div>
<div class="toc">
<dl>
<dt>
<span class="sect2">
<a href="moreinfo.html#contact_us">Contact Us</a>
</span>
</dt>
</dl>
</div>
<p>
Beyond this manual, you may also find the following sources of
information useful when building a JE application:
</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>
<a class="ulink" href="http://docs.oracle.com/cd/E17277_02/html/TransactionGettingStarted/index.html" target="_top">
Berkeley DB, Java Edition Getting Started with Transaction Processing
</a>
</p>
</li>
<li>
<p>
<a class="ulink" href="http://docs.oracle.com/cd/E17277_02/html/ReplicationGuide/index.html" target="_top">
Berkeley DB, Java Edition Getting Started with High Availability Applications
</a>
</p>
</li>
<li>
<p>
<span>
</span>
<a class="ulink" href="http://docs.oracle.com/cd/E17277_02/html/java/index.html" target="_top">
Berkeley DB, Java Edition Javadoc
</a>
</p>
</li>
<li>
<p>
<a class="ulink" href="http://docs.oracle.com/cd/E17277_02/html/collections/tutorial/index.html" target="_top">
Berkeley DB, Java Edition Collections Tutorial
</a>
</p>
</li>
</ul>
</div>
<span>
<p>
To download the latest
<span>Berkeley DB Java Edition</span>
documentation along with white papers and other collateral,
visit <a class="ulink" href="http://www.oracle.com/technetwork/indexes/documentation/index.html" target="_top">http://www.oracle.com/technetwork/indexes/documentation/index.html</a>.
</p>
<p>
For the latest version of the Oracle
<span>Berkeley DB Java Edition</span>
downloads, visit
<a class="ulink" href="http://www.oracle.com/technetwork/database/database-technologies/berkeleydb/downloads/index.html" target="_top">http://www.oracle.com/technetwork/database/database-technologies/berkeleydb/downloads/index.html</a>.
</p>
</span>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="contact_us"></a>Contact Us</h3>
</div>
</div>
</div>
<p>
You can post your comments and questions at the Oracle
Technology (OTN) forum for
<span>
Oracle Berkeley DB Java Edition at: <a class="ulink" href="https://forums.oracle.com/forums/forum.jspa?forumID=273" target="_top">https://forums.oracle.com/forums/forum.jspa?forumID=273</a>.
</span>
</p>
<p>
For sales or support information, email to:
<a class="ulink" href="mailto:berkeleydb-info_us@oracle.com" target="_top">berkeleydb-info_us@oracle.com</a>
You can subscribe to a low-volume email announcement list for
the Berkeley DB product family by sending email to:
<a class="ulink" href="mailto:bdb-join@oss.oracle.com" target="_top">bdb-join@oss.oracle.com</a>
</p>
</div>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="preface.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="preface.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="introduction.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Preface </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Chapter 1. Introduction to Berkeley DB Java Edition </td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,89 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Multiprocess Applications</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="concurrentProcessing.html" title="Appendix A. Concurrent Processing in Berkeley DB Java Edition" />
<link rel="prev" href="concurrentProcessing.html" title="Appendix A. Concurrent Processing in Berkeley DB Java Edition" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Multiprocess Applications</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="concurrentProcessing.html">Prev</a> </td>
<th width="60%" align="center">Appendix A. Concurrent Processing in Berkeley DB Java Edition</th>
<td width="20%" align="right"> </td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="multiprocess"></a>Multiprocess Applications</h2>
</div>
</div>
</div>
<p>
Note the following if you are writing an application that wants to access JE databases from multiple
processes:
</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>
In JE, you must use environments. Further, a database can be opened for write access only if the
environment is opened for write access. Finally, only one process may have an environment opened for
write access at a time.
</p>
</li>
<li>
<p>
If your process attempts to open an environment for write, and another process has already opened that
environment for write, then the open will fail. In this event, the process must either exit or open the
environment as read-only.
</p>
</li>
<li>
<p>
A process that opens an environment for read-only receives a snapshot of the data in that environment.
If another process modifies the environment's databases in any way, the read-only version of the data
will not be updated until the read-only process closes and reopens the environment (and by extension all
databases in that environment).
</p>
</li>
</ul>
</div>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="concurrentProcessing.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="concurrentProcessing.html">Up</a>
</td>
<td width="40%" align="right"> </td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Appendix A. Concurrent Processing in Berkeley DB Java Edition </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> </td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,156 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>MyDbEnv</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="dpl_example.html" title="Chapter 6. A DPL Example" />
<link rel="prev" href="inventoryclass.html" title="Inventory.java" />
<link rel="next" href="dataaccessorclass.html" title="DataAccessor.java" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">MyDbEnv</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="inventoryclass.html">Prev</a> </td>
<th width="60%" align="center">Chapter 6. A DPL Example</th>
<td width="20%" align="right"> <a accesskey="n" href="dataaccessorclass.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="mydbenv-persist"></a>MyDbEnv</h2>
</div>
</div>
</div>
<p>
The applications that we are building for our example both
must open and close environments and entity stores. One
of our applications is writing to the entity store, so this
application needs to open the store as read-write. It also
wants to be able to create the store if it does not exist.
</p>
<p>
Our second application only reads from the store. In this
case, the store should be opened as read-only.
</p>
<p>
We perform these activities by creating a single class that
is responsible for opening and closing our store and
environment. This class is shared by both our applications.
To use it, callers need to only provide the path to the
environment home directory, and to indicate whether the
object is meant to be read-only. The class implementation
is as follows:
</p>
<pre class="programlisting">package persist.gettingStarted;
import java.io.File;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;
import com.sleepycat.persist.EntityStore;
import com.sleepycat.persist.StoreConfig;
public class MyDbEnv {
private Environment myEnv;
private EntityStore store;
// Our constructor does nothing
public MyDbEnv() {}
// The setup() method opens the environment and store
// for us.
public void setup(File envHome, boolean readOnly)
throws DatabaseException {
EnvironmentConfig myEnvConfig = new EnvironmentConfig();
StoreConfig storeConfig = new StoreConfig();
myEnvConfig.setReadOnly(readOnly);
storeConfig.setReadOnly(readOnly);
// If the environment is opened for write, then we want to be
// able to create the environment and entity store if
// they do not exist.
myEnvConfig.setAllowCreate(!readOnly);
storeConfig.setAllowCreate(!readOnly);
// Open the environment and entity store
myEnv = new Environment(envHome, myEnvConfig);
store = new EntityStore(myEnv, "EntityStore", storeConfig);
}
// Return a handle to the entity store
public EntityStore getEntityStore() {
return store;
}
// Return a handle to the environment
public Environment getEnv() {
return myEnv;
}
// Close the store and environment.
public void close() {
if (store != null) {
try {
store.close();
} catch(DatabaseException dbe) {
System.err.println("Error closing store: " +
dbe.toString());
System.exit(-1);
}
}
if (myEnv != null) {
try {
// Finally, close the environment.
myEnv.close();
} catch(DatabaseException dbe) {
System.err.println("Error closing MyDbEnv: " +
dbe.toString());
System.exit(-1);
}
}
}
} </pre>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="inventoryclass.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="dpl_example.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="dataaccessorclass.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Inventory.java </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> DataAccessor.java</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,243 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Chapter 5. Saving and Retrieving Objects</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="dpl.html" title="Part I. Programming with the Direct Persistence Layer" />
<link rel="prev" href="dplindexcreate.html" title="Creating Indexes" />
<link rel="next" href="simpleda.html" title="SimpleDA.class" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Chapter 5. Saving and Retrieving Objects</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="dplindexcreate.html">Prev</a> </td>
<th width="60%" align="center">Part I. Programming with the Direct Persistence Layer</th>
<td width="20%" align="right"> <a accesskey="n" href="simpleda.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="chapter" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title"><a id="persist_access"></a>Chapter 5. Saving and Retrieving Objects</h2>
</div>
</div>
</div>
<div class="toc">
<p>
<b>Table of Contents</b>
</p>
<dl>
<dt>
<span class="sect1">
<a href="persist_access.html#simpleentity">A Simple Entity Class</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="simpleda.html">SimpleDA.class</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="simpleput.html">Placing Objects in an Entity Store</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="simpleget.html">Retrieving Objects from an Entity Store</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="getmultiple.html">Retrieving Multiple Objects</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect2">
<a href="getmultiple.html#dpl_cursor_initialize">Cursor Initialization</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="getmultiple.html#dpl_dups">Working with Duplicate Keys</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="getmultiple.html#dpl_cursor_range">Key Ranges</a>
</span>
</dt>
</dl>
</dd>
<dt>
<span class="sect1">
<a href="dpl_entityjoin.html">Join Cursors</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="dpl_delete.html">Deleting Entity Objects</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="dpl_replace.html">Replacing Entity Objects</a>
</span>
</dt>
</dl>
</div>
<p>
To store an object in an <code class="classname">EntityStore</code> you
must annotate the class appropriately and then store it using
<code class="methodname">PrimaryIndex.put()</code>.
</p>
<p>
To retrieve and object from an <code class="classname">EntityStore</code>
you use the <code class="methodname">get()</code> method from either the
<code class="classname">PrimaryIndex</code> or
<code class="classname">SecondaryIndex</code>, whichever is most
appropriate for your application.
</p>
<p>
In both cases, it simplifies things greatly if you create a data
accessor class to organize your indexes.
</p>
<p>
In the next few sections we:
</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>
Create an entity class that is ready to be stored
in an entity store. This class will have both a
primary index (required) declared for it, as well
as a secondary index (which is optional).
</p>
<p>
See the next section for this implementation.
</p>
</li>
<li>
<p>
Create a data accessor class which is used to
organize our data.
</p>
<p>
See <a class="xref" href="simpleda.html" title="SimpleDA.class">SimpleDA.class</a>
for this implementation.
</p>
</li>
<li>
<p>
Create a simple class that is used to put objects
to our entity store.
</p>
<p>
See <a class="xref" href="simpleput.html" title="Placing Objects in an Entity Store">Placing Objects in an Entity Store</a>
for this implementation.
</p>
</li>
<li>
<p>
Create another class that retrieves objects from
our entity store.
</p>
<p>
See <a class="xref" href="simpleget.html" title="Retrieving Objects from an Entity Store">Retrieving Objects from an Entity Store</a>
for this implementation.
</p>
</li>
</ol>
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="simpleentity"></a>A Simple Entity Class</h2>
</div>
</div>
</div>
<p>
For clarity's sake, this entity class is as simple a class as we can write.
It contains only two data members, both of which are set
and retrieved by simple setter and getter methods. Beyond
that, by design this class does not do anything of particular
interest.
</p>
<p>
Its implementation is as follows:
</p>
<pre class="programlisting">package persist.gettingStarted;
import com.sleepycat.persist.model.Entity;
import com.sleepycat.persist.model.PrimaryKey;
import static com.sleepycat.persist.model.Relationship.*;
import com.sleepycat.persist.model.SecondaryKey;
@Entity
public class SimpleEntityClass {
// Primary key is pKey
@PrimaryKey
private String pKey;
// Secondary key is the sKey
@SecondaryKey(relate=MANY_TO_ONE)
private String sKey;
public void setPKey(String data) {
pKey = data;
}
public void setSKey(String data) {
sKey = data;
}
public String getPKey() {
return pKey;
}
public String getSKey() {
return sKey;
}
} </pre>
</div>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="dplindexcreate.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="dpl.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="simpleda.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Creating Indexes </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> SimpleDA.class</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,316 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Chapter 3. Direct Persistence Layer First Steps</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="dpl.html" title="Part I. Programming with the Direct Persistence Layer" />
<link rel="prev" href="dpl.html" title="Part I. Programming with the Direct Persistence Layer" />
<link rel="next" href="persistobject.html" title="Persistent Objects" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Chapter 3. Direct Persistence Layer First Steps</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="dpl.html">Prev</a> </td>
<th width="60%" align="center">Part I. Programming with the Direct Persistence Layer</th>
<td width="20%" align="right"> <a accesskey="n" href="persistobject.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="chapter" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title"><a id="persist_first"></a>Chapter 3. Direct Persistence Layer First Steps</h2>
</div>
</div>
</div>
<div class="toc">
<p>
<b>Table of Contents</b>
</p>
<dl>
<dt>
<span class="sect1">
<a href="persist_first.html#entitystore">Entity Stores</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect2">
<a href="persist_first.html#persist-open">Opening and Closing Environments and Stores</a>
</span>
</dt>
</dl>
</dd>
<dt>
<span class="sect1">
<a href="persistobject.html">Persistent Objects</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="saveret.html">Saving and Retrieving Data</a>
</span>
</dt>
</dl>
</div>
<p>
This chapter guides you through the first few steps required to
use the DPL with your application. These steps include:
</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>
Opening your environment as was described in
<span>
<a class="xref" href="env.html#envopen" title="Opening Database Environments">Opening Database Environments</a>.
</span>
</p>
</li>
<li>
<p>
Opening your entity store.
</p>
</li>
<li>
<p>
Identifying the classes that you want to store in
JE as either a <code class="literal">persistent</code>
class or an <code class="literal">entity</code>.
</p>
</li>
</ol>
</div>
<p>
Once you have done these things, you can write your classes to
the JE databases, read them back from the databases, delete
them from the databases, and so forth. These activities are
described in the chapters that follow in this part of this manual.
</p>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="entitystore"></a>Entity Stores</h2>
</div>
</div>
</div>
<div class="toc">
<dl>
<dt>
<span class="sect2">
<a href="persist_first.html#persist-open">Opening and Closing Environments and Stores</a>
</span>
</dt>
</dl>
</div>
<p>
Entity stores are the basic unit of storage that you use with the DPL. That is, it
is a unit of encapsulation for the classes that you want to store in JE. Under
the hood it actually interacts with JE databases, but the DPL provides a layer
of abstraction from the underlying JE APIs. The store, therefore, provides a
simplified mechanism by which you read and write your stored classes. By using a
store, you have access to your classes that is more simplified than if you were
interacting with databases directly, but this simplified access comes at the cost of
reduced flexibility.
</p>
<p>
Entity stores have configurations in the same way that environments have
configurations. You can use a <code class="classname">StoreConfig</code> object
to identify store properties. Among these are methods that allow you to declare
whether:
</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>
the store can be created if it does not exist at the time
it is opened. Use the
<code class="methodname">StoreConfig.setAllowCreate()</code>
method to set this.
</p>
</li>
<li>
<p>
deferred writes are allowed for the store. Use the
<code class="methodname">StoreConfig.setDeferredWrite()</code>
method to set this. See
<a class="xref" href="databases.html#dwdatabase" title="Deferred Write Databases">Deferred Write Databases</a>
for general information on deferred write
databases.
</p>
</li>
<li>
<p>
the store is read-only. Use the
<code class="methodname">StoreConfig.setReadOnly()</code>
method to set this.
</p>
</li>
<li>
<p>
the store supports transactions. Use the
<code class="methodname">StoreConfig.setTransactional()</code>
method to set this.
</p>
<p>
Writing JE transactional applications is described in the
<em class="citetitle">Berkeley DB, Java Edition Getting Started with Transaction Processing</em> guide.
</p>
</li>
</ul>
</div>
<p>
<code class="classname">EntityStore</code> objects also provide methods for retrieving
information about the store, such as:
</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>
the store's name. Use the
<code class="methodname">EntityStore.getStoreName()</code>
method to retrieve this.
</p>
</li>
<li>
<p>
a handle to the environment in which the store is opened. Use the
<code class="methodname">EntityStore.getEnvironment</code>
method to retrieve this handle.
</p>
</li>
</ul>
</div>
<p>
You can also use the <code class="classname">EntityStore</code> to
retrieve all the primary and secondary indexes related to a given type of entity
object contained in the store. See <a class="xref" href="persist_index.html" title="Chapter 4. Working with Indices">Working with Indices</a> for
more information.
</p>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="persist-open"></a>Opening and Closing Environments and Stores</h3>
</div>
</div>
</div>
<p>
As described in
<span>
<a class="xref" href="env.html" title="Chapter 2. Database Environments">Database Environments</a>,
</span>
an
<span class="emphasis"><em>environment</em></span> is a unit of
encapsulation for JE databases. It also provides a
handle by which activities common across the databases
can be managed.
</p>
<p>
To use an entity store, you must first open an environment and then provide that
environment handle to the <code class="classname">EntityStore</code> constructor.
</p>
<p>
For example, the following code fragment configures both
the environment and the entity store such that they can
be created if they do not exist. Both the environment and
the entity store are then opened.
</p>
<pre class="programlisting">package persist.gettingStarted;
import java.io.File;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;
import com.sleepycat.persist.EntityStore;
import com.sleepycat.persist.StoreConfig;
...
private Environment myEnv;
private EntityStore store;
try {
EnvironmentConfig myEnvConfig = new EnvironmentConfig();
StoreConfig storeConfig = new StoreConfig();
myEnvConfig.setAllowCreate(!readOnly);
storeConfig.setAllowCreate(!readOnly);
// Open the environment and entity store
myEnv = new Environment(envHome, myEnvConfig);
store = new EntityStore(myEnv, "EntityStore", storeConfig);
} catch(DatabaseException dbe) {
System.err.println("Error opening environment and store: " +
dbe.toString());
System.exit(-1);
} </pre>
<p>
As always, before you exit your program you should close both
your store and your environment. It is recommended that you close your store before you close your
environment.
</p>
<pre class="programlisting">if (store != null) {
try {
store.close();
} catch(DatabaseException dbe) {
System.err.println("Error closing store: " +
dbe.toString());
System.exit(-1);
}
}
if (myEnv != null) {
try {
// Finally, close environment.
myEnv.close();
} catch(DatabaseException dbe) {
System.err.println("Error closing MyDbEnv: " +
dbe.toString());
System.exit(-1);
}
} </pre>
</div>
</div>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="dpl.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="dpl.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="persistobject.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Part I. Programming with the Direct Persistence Layer </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Persistent Objects</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,245 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Chapter 4. Working with Indices</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="dpl.html" title="Part I. Programming with the Direct Persistence Layer" />
<link rel="prev" href="saveret.html" title="Saving and Retrieving Data" />
<link rel="next" href="dplindexcreate.html" title="Creating Indexes" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Chapter 4. Working with Indices</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="saveret.html">Prev</a> </td>
<th width="60%" align="center">Part I. Programming with the Direct Persistence Layer</th>
<td width="20%" align="right"> <a accesskey="n" href="dplindexcreate.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="chapter" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title"><a id="persist_index"></a>Chapter 4. Working with Indices</h2>
</div>
</div>
</div>
<div class="toc">
<p>
<b>Table of Contents</b>
</p>
<dl>
<dt>
<span class="sect1">
<a href="persist_index.html#dplindexaccess">Accessing Indexes</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect2">
<a href="persist_index.html#primaryindexaccess">Accessing Primary Indices</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="persist_index.html#secondaryindexaccess">Accessing Secondary Indices</a>
</span>
</dt>
</dl>
</dd>
<dt>
<span class="sect1">
<a href="dplindexcreate.html">Creating Indexes</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect2">
<a href="dplindexcreate.html#dplprimaryidxdecl">Declaring Primary Indexes</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="dplindexcreate.html#dplsecondaryidxdecl">Declaring Secondary Indexes</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="dplindexcreate.html#foreignkey">Foreign Key Constraints</a>
</span>
</dt>
</dl>
</dd>
</dl>
</div>
<p>
All entity classes stored in JE using the DPL must have a
primary index, or key, identified for them. All such classes may
also have one or more secondary keys declared for them. This
chapter describes primary and secondary indexes in detail, and
shows how to access the indexes created for a given entity class.
</p>
<p>
One way to organize access to your primary and secondary
indexes is to create a <span class="emphasis"><em>data accessor</em></span>
class. We show an implementation of a data accessor class in
<a class="xref" href="simpleda.html" title="SimpleDA.class">SimpleDA.class</a>.
</p>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="dplindexaccess"></a>Accessing Indexes</h2>
</div>
</div>
</div>
<div class="toc">
<dl>
<dt>
<span class="sect2">
<a href="persist_index.html#primaryindexaccess">Accessing Primary Indices</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="persist_index.html#secondaryindexaccess">Accessing Secondary Indices</a>
</span>
</dt>
</dl>
</div>
<p>
In order to retrieve any object from an entity store, you
must access at least the primary index for that object.
Different entity classes stored in an entity store can have
different primary indexes, but all entity classes must have a
primary index declared for it. The primary index is just
the default index used for the class. (That is, it is the
data's primary <span class="emphasis"><em>key</em></span> for the underlying database.)
</p>
<p>
Entity classes can optionally have secondary indexes
declared for them. In order to access these secondary
indexes, you must first access the primary index.
</p>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="primaryindexaccess"></a>Accessing Primary Indices</h3>
</div>
</div>
</div>
<p>
You retrieve a primary index using the
<code class="methodname">EntityStore.getPrimaryIndex()</code>
method. To do this, you indicate the index key type
(that is, whether it is a String, Integer, and
so forth) and the class of the entities stored
in the index.
</p>
<p>
For example, the following retrieves the
primary index for an <code class="classname">Inventory</code>
class (we provide an implementation of this class in
<a class="xref" href="inventoryclass.html" title="Inventory.java">Inventory.java</a>).
These index keys are of type <code class="classname">String</code>.
</p>
<pre class="programlisting">PrimaryIndex&lt;String,Inventory&gt; inventoryBySku =
store.getPrimaryIndex(String.class, Inventory.class); </pre>
</div>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="secondaryindexaccess"></a>Accessing Secondary Indices</h3>
</div>
</div>
</div>
<p>
You retrieve a secondary index using the
<code class="methodname">EntityStore.getSecondaryIndex()</code>
method. Because secondary indices actually
refer to a primary index somewhere in your data
store, to access a secondary index you:
</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>
Provide the primary index as
returned by
<code class="methodname">EntityStore.getPrimaryIndex()</code>.
</p>
</li>
<li>
<p>
Identify the key data type used by
the secondary index
(<code class="classname">String</code>,
<code class="classname">Long</code>,
and so forth).
</p>
</li>
<li>
<p>
Identify the name of the
secondary key field.
When you declare the
<code class="classname">SecondaryIndex</code>
object, you identify the entity class
to which the secondary index
must refer.
</p>
</li>
</ol>
</div>
<p>
For example, the following first retrieves the
primary index, and then uses that to retrieve a secondary
index. The secondary key is held by the
<code class="literal">itemName</code> field of the
<code class="classname">Inventory</code> class.
</p>
<pre class="programlisting">PrimaryIndex&lt;String,Inventory&gt; inventoryBySku =
store.getPrimaryIndex(String.class, Inventory.class);
SecondaryIndex&lt;String,String,Inventory&gt; inventoryByName =
store.getSecondaryIndex(inventoryBySku, String.class, "itemName"); </pre>
</div>
</div>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="saveret.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="dpl.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="dplindexcreate.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Saving and Retrieving Data </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Creating Indexes</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,147 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Persistent Objects</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="persist_first.html" title="Chapter 3. Direct Persistence Layer First Steps" />
<link rel="prev" href="persist_first.html" title="Chapter 3. Direct Persistence Layer First Steps" />
<link rel="next" href="saveret.html" title="Saving and Retrieving Data" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Persistent Objects</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="persist_first.html">Prev</a> </td>
<th width="60%" align="center">Chapter 3. Direct Persistence Layer First Steps</th>
<td width="20%" align="right"> <a accesskey="n" href="saveret.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="persistobject"></a>Persistent Objects</h2>
</div>
</div>
</div>
<p>
When using the DPL, you store data in the underlying
JE databases by making objects
<span class="emphasis"><em>persistent</em></span>. You do this using Java
annotations that both identify the type of persistent
object you are declaring, as well as the primary and
secondary indices.
</p>
<p>
The following are the annotations you will use with your
DPL persistent classes:
</p>
<div class="informaltable">
<table border="1" width="80%">
<colgroup>
<col />
<col />
</colgroup>
<thead>
<tr>
<th>Annotation</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>@Entity</td>
<td>
Declares an entity class; that is, a class with a primary index
and optionally one or more indices.
</td>
</tr>
<tr>
<td>@Persistent</td>
<td>
Declares a persistent class; that is, a class used by an entity
class. They do not have indices but instead are are stored or
retrieved when an entity class makes direct use of them.
</td>
</tr>
<tr>
<td>@PrimaryKey</td>
<td>
Declares a specific data member in an entity class to be the
primary key for that object. This annotation must be used one
and only one time for every entity class.
</td>
</tr>
<tr>
<td>@SecondaryKey</td>
<td>
Declares a specific data member in an entity class to be a
secondary key for that object. This annotation is optional, and
can be used multiple times for an entity class.
</td>
</tr>
</tbody>
</table>
</div>
<p>
For example, the following is declared to be an entity class:
</p>
<pre class="programlisting">package persist.gettingStarted;
import com.sleepycat.persist.model.Entity;
import com.sleepycat.persist.model.PrimaryKey;
@Entity
public class ExampleEntity {
// The primary key must be unique in the database.
@PrimaryKey
private String aPrimaryKey;
@SecondaryKey(relate=MANY_TO_ONE)
private String aSecondaryKey;
...
// The remainder of the class' implementation is purposefully
// omitted in the interest of brevity.
...
} </pre>
<p>
We discuss primary and secondary keys in more detail in <a class="xref" href="persist_index.html" title="Chapter 4. Working with Indices">Working with Indices</a>.
</p>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="persist_first.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="persist_first.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="saveret.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Chapter 3. Direct Persistence Layer First Steps </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Saving and Retrieving Data</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,174 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Preface</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="prev" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="next" href="moreinfo.html" title="For More Information" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Preface</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="index.html">Prev</a> </td>
<th width="60%" align="center"> </th>
<td width="20%" align="right"> <a accesskey="n" href="moreinfo.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="preface" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title"><a id="preface"></a>Preface</h2>
</div>
</div>
</div>
<div class="toc">
<p>
<b>Table of Contents</b>
</p>
<dl>
<dt>
<span class="sect1">
<a href="preface.html#conventions">Conventions Used in this Book</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="moreinfo.html">For More Information</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect2">
<a href="moreinfo.html#contact_us">Contact Us</a>
</span>
</dt>
</dl>
</dd>
</dl>
</div>
<p>
Welcome to Berkeley DB Java Edition (JE).
<span>
This document introduces JE, version 12<span class="emphasis"><em>c</em></span> Release 2.
</span>
</p>
<p>
This document is intended to provide a rapid introduction
to the JE API set and related concepts. The goal of this
document is to provide you with an efficient mechanism with which
you can evaluate JE against your project's technical
requirements. As such, this document is intended for
<span>Java</span>
developers and senior software architects who are looking for an
<span>
in-process data management solution.
</span>
No prior experience with Berkeley DB Java Edition is expected or required.
</p>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="conventions"></a>Conventions Used in this Book</h2>
</div>
</div>
</div>
<p>
The following typographical conventions are used within in this manual:
</p>
<p>
Class names are represented in <code class="classname">monospaced font</code>, as are <code class="methodname">method
names</code>. For example:
<span>"The <code class="methodname">Environment.openDatabase()</code> method
returns a <code class="classname">Database</code> class object."</span>
</p>
<p>
Variable or non-literal text is presented in <span class="emphasis"><em>italics</em></span>. For example: "Go to your
<span class="emphasis"><em>JE_HOME</em></span>
directory."
</p>
<p>
Program examples are displayed in a <code class="classname">monospaced font</code> on a shaded background.
For example:
</p>
<pre class="programlisting">import com.sleepycat.je.Environment;
...
// Open the environment. Allow it to be created if it does not
// already exist.
Environment myDbEnv;</pre>
<p>
In some situations, programming examples are updated from one chapter to the next. When
this occurs, the new code is presented in <strong class="userinput"><code>monospaced bold</code></strong> font. For example:
</p>
<pre class="programlisting">import com.sleepycat.je.Environment;
<strong class="userinput"><code>import com.sleepycat.je.EnvironmentConfig;
import java.io.File;</code></strong>
...
// Open the environment. Allow it to be created if it does not
// already exist.
Environment myDbEnv;
<strong class="userinput"><code>EnvironmentConfig envConfig = new EnvironmentConfig();
envConfig.setAllowCreate(true);
myDbEnv = new Environment(new File("/export/dbEnv"), envConfig);</code></strong> </pre>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;">
<h3 class="title">Note</h3>
<p>
Finally, notes of interest are represented using a note block such
as this.
</p>
</div>
</div>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="index.html">Prev</a> </td>
<td width="20%" align="center"> </td>
<td width="40%" align="right"> <a accesskey="n" href="moreinfo.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Getting Started with Berkeley DB Java Edition </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> For More Information</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,125 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Reading Secondary Databases</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="indexes.html" title="Chapter 10. Secondary Databases" />
<link rel="prev" href="secondaryProps.html" title="Secondary Database Properties" />
<link rel="next" href="secondaryDelete.html" title="Deleting Secondary Database Records" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Reading Secondary Databases</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="secondaryProps.html">Prev</a> </td>
<th width="60%" align="center">Chapter 10. Secondary Databases</th>
<td width="20%" align="right"> <a accesskey="n" href="secondaryDelete.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="readSecondary"></a>Reading Secondary Databases</h2>
</div>
</div>
</div>
<p>
Like a primary database, you can read records from your secondary
database either by using the
<span>
<code class="methodname">SecondaryDatabase.get()</code> method,
</span>
or by using
<span>a <code class="classname">SecondaryCursor</code>.</span>
The main difference between reading secondary and primary databases is that when
you read a secondary database record, the secondary record's data is not
returned to you. Instead, the primary key and data corresponding to the
secondary key are returned to you.
</p>
<p>
For example, assuming your secondary database contains keys related
to a person's full name:
</p>
<a id="je_index6"></a>
<pre class="programlisting">package je.gettingStarted;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.LockMode;
import com.sleepycat.je.OperationStatus;
import com.sleepycat.je.SecondaryDatabase;
...
try {
// Omitting all database and environment opens
...
String searchName = "John Doe";
DatabaseEntry searchKey =
new DatabaseEntry(searchName.getBytes("UTF-8"));
DatabaseEntry primaryKey = new DatabaseEntry();
DatabaseEntry primaryData = new DatabaseEntry();
// Get the primary key and data for the user 'John Doe'.
OperationStatus retVal = mySecondaryDatabase.get(null, searchKey,
primaryKey,
primaryData,
LockMode.DEFAULT);
} catch (Exception e) {
// Exception handling goes here
}</pre>
<p>
Note that, just like
<span><code class="methodname">Database.get()</code>, </span>
if your secondary database supports duplicate records then
<code class="methodname">SecondaryDatabase.get()</code>
only return the first record found in a matching duplicates set. If you
want to see all the records related to a specific secondary key, then use a
<span>
<code class="classname">SecondaryCursor</code> (described in <a class="xref" href="secondaryCursor.html" title="Using Secondary Cursors">
<span>Using Secondary Cursors</span>
</a>).
</span>
</p>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="secondaryProps.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="indexes.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="secondaryDelete.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Secondary Database Properties </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Deleting Secondary Database Records</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,103 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>JE Backup and Restore</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="introduction.html" title="Chapter 1. Introduction to Berkeley DB Java Edition" />
<link rel="prev" href="applicationoverview.html" title="The JE Application" />
<link rel="next" href="jca.html" title="JCA Support" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">JE Backup and Restore</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="applicationoverview.html">Prev</a> </td>
<th width="60%" align="center">Chapter 1. Introduction to Berkeley DB Java Edition </th>
<td width="20%" align="right"> <a accesskey="n" href="jca.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="restore"></a>JE Backup and Restore</h2>
</div>
</div>
</div>
<p>
To backup your database, copy the log files (the
<code class="literal">.jdb</code> files) starting from the lowest
numbered log file to the highest numbered log file to your
backup media. Be sure to copy the bytes of the individual
database files in order from the lowest to the highest. You do
not have to close your database or otherwise cease database
operations when you do this.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;">
<h3 class="title">Note</h3>
<p>
Note that if you are using subdirectories to store your log
files, then you should copy those subdirectories and their
contents instead of simply copying individual files.
Multiple subdirectories can be used to improve JE
throughput, but this feature is not turned on by default.
See <a class="xref" href="env.html#multisubdir" title="Multiple Environment Subdirectories">Multiple Environment Subdirectories</a>
for information on how to configure this feature.
</p>
</div>
<p>
Restoring a JE database from a backup consists of closing your
JE environment, copying archived log files back into your
environment directory and then opening your JE environment
again. If you are using subdirectories to store your log files,
then make sure to copy those subdirectories back into the
environment home directory, and make sure the same log files are in
each subdirectory as was there when you took the backup.
</p>
<p>
Note that whenever a JE environment is opened, JE runs
<span class="emphasis"><em>normal recovery</em></span>. This involves bringing your
database into a consistent state given the changed data found in the
database. If you are using transactions during normal operations, then
JE automatically runs checkpoints for you so as to limit the time
required to run this recovery. In any case, running normal recovery is a
routine operation, while performing database restores is not.
</p>
<p>
For more information on JE backup and restores, and on checkpoints, see
<a class="xref" href="backuprestore.html" title="Chapter 11. Backing up and Restoring Berkeley DB Java Edition Applications">Backing up and Restoring Berkeley DB Java Edition Applications</a>.
</p>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="applicationoverview.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="introduction.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="jca.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">The JE Application </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> JCA Support</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,123 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Saving and Retrieving Data</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="persist_first.html" title="Chapter 3. Direct Persistence Layer First Steps" />
<link rel="prev" href="persistobject.html" title="Persistent Objects" />
<link rel="next" href="persist_index.html" title="Chapter 4. Working with Indices" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Saving and Retrieving Data</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="persistobject.html">Prev</a> </td>
<th width="60%" align="center">Chapter 3. Direct Persistence Layer First Steps</th>
<td width="20%" align="right"> <a accesskey="n" href="persist_index.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="saveret"></a>Saving and Retrieving Data</h2>
</div>
</div>
</div>
<p>
All data stored using the DPL has one primary index and
zero or more secondary indices associated with it.
(Sometimes these are referred to as the primary and
secondary <span class="emphasis"><em>keys</em></span>.) So to store data under the DPL, you must:
</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>
Declare a class to be an entity class.
</p>
</li>
<li>
<p>
Identify the features on the class which
represent indexed material.
</p>
</li>
<li>
<p>
Retrieve the store's primary index for a
given class using the
<code class="methodname">EntityStore.getPrimaryIndex()</code>
method.
</p>
</li>
<li>
<p>
Put class objects to the store using the
<code class="methodname">PrimaryIndex.put()</code>
method.
</p>
</li>
</ol>
</div>
<p>
In order to retrieve an object from the store, you use
the index that is most convenient for your purpose. This
may be the primary index, or it may be some other
secondary index that you declared on your entity class.
</p>
<p>
You obtain a primary index in the same was as when you
put the object to the store: using
<code class="methodname">EntityStore.getPrimaryIndex()</code>.
You can get a secondary index for the store using the
<code class="methodname">EntityStore.getSecondaryIndex()</code>
method. Note that
<code class="methodname">getSecondaryIndex()</code> requires you
to provide a <code class="classname">PrimaryIndex</code> class
instance when you call it, so a class's primary index is
always required when retrieving objects from an entity
store.
</p>
<p>
Usually all of the activity surrounding saving and
retrieving data is organized within a class or classes
specialized to that purpose. We describe the construction
of these data accessor classes in <a class="xref" href="simpleda.html" title="SimpleDA.class">SimpleDA.class</a>. But before you perform
any entity store activity, you need to understand
indexes. We therefore describe them in the next chapter.
</p>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="persistobject.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="persist_first.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="persist_index.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Persistent Objects </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Chapter 4. Working with Indices</td>
</tr>
</table>
</div>
</body>
</html>

View file

@ -0,0 +1,155 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Using Secondary Cursors</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Java Edition" />
<link rel="up" href="indexes.html" title="Chapter 10. Secondary Databases" />
<link rel="prev" href="secondaryDelete.html" title="Deleting Secondary Database Records" />
<link rel="next" href="joins.html" title="Database Joins" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.2.7.5</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">
<span xmlns="http://www.w3.org/1999/xhtml">Using Secondary Cursors</span>
</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="secondaryDelete.html">Prev</a> </td>
<th width="60%" align="center">Chapter 10. Secondary Databases</th>
<td width="20%" align="right"> <a accesskey="n" href="joins.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="secondaryCursor"></a>
<span>Using Secondary Cursors</span>
</h2>
</div>
</div>
</div>
<p>
Just like cursors on a primary database, you can use
<span>secondary cursors</span>
to iterate over the records in a secondary database. Like
<span>normal cursors,</span>
you can also use
<span>secondary cursors</span>
to search for specific records in a database, to seek to the first
or last record in the database, to get the next duplicate record,
<span>to get the next non-duplicate record,</span>
and so forth. For a complete description on cursors and their capabilities, see
<a class="xref" href="Cursors.html" title="Chapter 9. Using Cursors">Using Cursors</a>.
</p>
<p>
However, when you use
<span>secondary cursors:</span>
</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>
Any data returned is the data contained on the primary database
record referenced by the secondary record.
</p>
</li>
<li>
<p>
<code class="methodname">SecondaryCursor.getSearchBoth()</code> and
related methods do not search based on a key/data pair. Instead, you
search based on a secondary key and a primary key. The data returned
is the primary data that most closely matches the two keys provided
for the search.
</p>
</li>
</ul>
</div>
<p>
For example, suppose you are using the databases, classes, and key
<span>creators</span>
described in <a class="xref" href="keyCreator.html" title="Implementing Key Creators">Implementing Key
<span>Creators</span>
</a>.
Then the following searches for a person's
name in the secondary database, and deletes all secondary and primary
records that use that name.
</p>
<a id="je_index8"></a>
<pre class="programlisting">package je.gettingStarted;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.LockMode;
import com.sleepycat.je.OperationStatus;
import com.sleepycat.je.SecondaryDatabase;
import com.sleepycat.je.SecondaryCursor;
...
try {
// Database and environment opens omitted for brevity
...
String secondaryName = "John Doe";
DatabaseEntry secondaryKey =
new DatabaseEntry(secondaryName.getBytes("UTF-8"));
DatabaseEntry foundData = new DatabaseEntry();
SecondaryCursor mySecCursor =
mySecondaryDatabase.openSecondaryCursor(null, null);
OperationStatus retVal = mySecCursor.getSearchKey(secondaryKey,
foundData,
LockMode.DEFAULT);
while (retVal == OperationStatus.SUCCESS) {
mySecCursor.delete();
retVal = mySecCursor.getNextDup(secondaryKey,
foundData,
LockMode.DEFAULT);
}
} catch (Exception e) {
// Exception handling goes here
}</pre>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="secondaryDelete.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="indexes.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="joins.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Deleting Secondary Database Records </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Database Joins</td>
</tr>
</table>
</div>
</body>
</html>

Some files were not shown because too many files have changed in this diff Show more