Chapter 5. Getting started with ObjectContext

Table of Contents

Creating the Main Class
Running Application

In this section we'll write a simple main class to run our application, and get a brief introduction to Cayenne ObjectContext.

Creating the Main Class

  • In Eclipse create a new class called "Main" in the "org.example.cayenne" package.

  • Create a standard "main" method to make it a runnable class:

    package org.example.cayenne;
    
    public class Main {
    
        public static void main(String[] args) {
    
        }
    }
  • The first thing you need to be able to access the database is to create a ServerRuntime object (which is essentially a wrapper around Cayenne stack) and use it to obtain an instance of an ObjectContext.

    package org.example.cayenne;
    
    import org.apache.cayenne.ObjectContext;
    import org.apache.cayenne.configuration.server.ServerRuntime;
    
    public class Main {
    
        public static void main(String[] args) {
            ServerRuntime cayenneRuntime = new ServerRuntime(
                    "cayenne-project.xml");
            ObjectContext context = cayenneRuntime.getContext();
        }
    }

    ObjectContext is an isolated "session" in Cayenne that provides all needed API to work with data. ObjectContext has methods to execute queries and manage persistent objects. We'll discuss them in the following sections. When the first ObjectContext is created in the application, Cayenne loads XML mapping files and creates a shared access stack that is later reused by other ObjectContexts.

Running Application

Let's check what happens when you run the application. But before we do that we need to add another dependency to the pom.xml - Apache Derby, our embedded database engine. The following piece of XML needs to be added to the <dependencies>...</dependencies> section, where we already have Cayenne jars:

<dependency>
   <groupId>org.apache.derby</groupId>
   <artifactId>derby</artifactId>
   <version>10.8.1.2</version>
</dependency>

Now we are ready to run. Right click the "Main" class in Eclipse and select "Run As > Java Application". In the console you'll see output similar to this, indicating that Cayenne stack has been started:

INFO: Loading XML configuration resource from file:cayenne-project.xml
INFO: loading user name and password.
INFO: Created connection pool: jdbc:derby:memory:testdb;create=true
    Driver class: org.apache.derby.jdbc.EmbeddedDriver
    Min. connections in the pool: 1
    Max. connections in the pool: 1

Note

How to Configure Cayenne Logging. Follow the instructions in the logging chapter to tweak verbosity of the logging output.