Cayenne User Documentation
Obtaining DataContext

Depending on deployment environment and application needs, Cayenne can be configured in a few different ways to make DataContext instances available. This is discussed in detail in deployment chapter. But basically it comes down to getting a hold of an instance of `ServerRuntime` and calling `getContext()` on it as described below.

### Obtaining a DataContext from the DI Runtime

    ServerRuntime runtime = ...
    ObjectContext context = runtime.getContext()

Note that every call to `getContext()` returns a new instance. Also note that it returns `ObjectContext` (an interface implemented by `DataContext`). If you need to use DataContext API not declared in ObjectContext, you may use a cast:

    ServerRuntime runtime = ...
    DataContext context = (DataContext) runtime.getContext()

But if you don't, we recommend to stick with ObjectContext in your code, as it makes the code more flexible and portable to the future versions of Cayenne.

### Retrieving Thread-Bound DataContext

An application can bind a context to a current execution thread (e.g. via `CayenneFilter` or manually). Later on the code that needs DB access can retrieve this DataContext without making any assumptions about the environment. This approach is universal and works in all types of applications (web, standalone, etc.). Previously bound context can be retrieved by calling `BaseContext.getThreadObjectContext()` static method. If no context was bound to the current thread, this method throws IllegalStateException (same rules for casting ObjectContext to DataContext as above apply) :

    // we are positive there is DataContext in the current thread, and do not want
    // to handle possible exception...
    DataContext context = (DataContext) BaseContext.getThreadObjectContext();

    // we want to handle the condition of no thread-bound context...
    try {
        DataContext context = (DataContext) BaseContext.getThreadObjectContext();
    }
    catch(IllegalStateException ex) {
        // handle failure
        ....
    }

.
Copyright ©2001-2010 Apache Software Foundation