The JE Application
Prev | Chapter 1. Introduction to Berkeley DB Java Edition | Next

## The JE Application

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.

Note that the core JE classes are all contained in the `com.sleepycat.je` package. In addition, this book describes some classes that are found in `com.sleepycat.je.bind`. The bind APIs are used for converting Java objects in and out of `byte` arrays.

### Database Environments

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 Databases for more information.

That said, JE always requires you to use a database environment. 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.

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.

You open a database environment by instantiating an `Environment` object. Your `Environment` instance is called an environment handle.

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 Berkeley DB, Java Edition Getting Started with Transaction Processing 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.

Environments are described in greater detail in Database Environments.

### Key-Data Pairs

JE stores and retrieves data using key-data pairs. The data portion of this is the data that you have decided to store in JE for future retrieval. The key is the information that you want to use to look up your stored data once it has been placed inside a JE database.

For example, if you were building a database that contained employee information, then the data 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.

The key, 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 Duplicate Data for more information.

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.

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.

### Storing Data

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.

#### Storing Data in the DPL

The DPL is used to store Java objects in an underlying series of databases. These databases are accessed using an `EntityStore` class object.

To use the DPL, you must decorate the classes you want to store with Java annotations that identify them as either an entity class or a persistent class.

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 `@Entity` java annotation.

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 `@Persistent` java annotation.

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 `@PrimaryKey` java annotation.

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.

Also, simple Java types, such as `java.lang.String` and `java.util.Date`, 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 `EntityStore`.

#### Storing Data using the Base API

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 `DatabaseEntry` instances. `DatabaseEntry` 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

Database records and `byte` array conversion are described in Database Records.

You store records in a `Database` by calling one of the put methods on a `Database` 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.

You can also retrieve, or get, records using the `Database` handle. Gets are performed by providing the key (and sometimes also the data) of the record that you want to retrieve.

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 `Cursor` class.

Databases are described in Databases. Cursors are described in Using Cursors.

### Duplicate Data

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. Duplicate data, then, occurs when two or more records have identical keys, but different data. By default, a `Database` does not allow duplicate data.

If your `Database` 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.

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 Retrieving Multiple Objects.

### Replacing and Deleting Entries

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 `delete()` method that is available on either its primary or secondary keys. If you use the `delete()` method available on the secondary key, then all objects referenced by that key are also deleted. See Deleting Entity Objects for more information.

If you are using the base API, then how you replace database records depends on whether duplicate data is allowed in the database.

If duplicate data is not allowed in the database, then simply calling `Database.put()` 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 `Database.delete()` method.

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.

To delete records using the base API, you can use either `Database.delete()` or `Cursor.delete()`. If duplicate data is not allowed in your database, then these two method behave identically. However, if duplicates are allowed in the database, then `Database.delete()` deletes every record that uses the provided key, while `Cursor.delete()` deletes just the record at which the cursor is currently positioned.

### Secondary Keys

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.

How you create and maintain secondary keys differs significantly, depending on whether you are using the DPL or the base API.

#### Using Secondaries with the DPL

Under the DPL, you declare a particular field to be a secondary key by using the `@SecondaryKey` 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 `ONE_TO_ONE` index, in which case the key is unique to the object. Or you could declare the key to be `MANY_TO_ONE`, in which case the key can be used for multiple objects in the data store.

Once you have identified secondary keys for a class, you can access those keys by using the `EntityStore.getSecondaryIndex()` method.

For more information, see Declaring Secondary Indexes.

#### Using Secondaries with the Base API.

When you are using the base API, you create and maintain secondary keys using a special type of a database, called a secondary database. When you are using secondary databases, the database that holds the data you are indexing is called the primary database.

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.

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.

You manage secondary databases using the `SecondaryDatabase` class. You identify how to create keys for your secondary databases by supplying an instance of a class that implements the `SecondaryKeyCreator` interface.

Secondary databases are described in Secondary Databases.

### Transactions

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.

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.

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.

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 `Database`, `Cursor`, or `Transaction` handle to relax its isolation guarantees.

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.

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.

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.

Using transactions with your JE applications is described in detail in the Berkeley DB, Java Edition Getting Started with Transaction Processing guide.

### JE Resources

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.

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.

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.

For more information on sizing the cache and on the background threads, see Administering Berkeley DB Java Edition Applications.

### Application Considerations

When building your JE application, be sure to think about the following things:

- 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 Database Records for more information.

- 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 Opening Databases for more information.

  If you are supporting duplicate records, you may also need to think about duplicate comparators (not just key comparators). See Using Comparators for more information.

- 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 Secondary Databases.

- What cache size do you need? See Sizing the Cache for information on how to size your cache.

- Does your application require transactions (most will). Transactions are described in the Berkeley DB, Java Edition Getting Started with Transaction Processing guide.

Prev | Up | Next
Chapter 1. Introduction to Berkeley DB Java Edition | Home | JE Backup and Restore