DataNucleus - Tutorial for JDO using MongoDB
An application can be JDO-enabled via many routes depending on the development process of the project in question. For example the project could use Eclipse as the IDE for developing classes. In that case the project would typically use the DataNucleus Eclipse plugin. Alternatively the project could use Ant, Maven or some other build tool. In this case this tutorial should be used as a guiding way for using DataNucleus in the application. The JDO process is quite straightforward.
- Prerequisite : Download DataNucleus AccessPlatform
- Step 1 : Define their persistence definition using Meta-Data.
- Step 2 : Define the "persistence-unit"
- Step 3 : Compile your classes, and instrument them (using the DataNucleus enhancer).
- Step 4 : Write your code to persist your objects within the DAO layer.
- Step 5 : Run your application.
The tutorial guides you through this. You can obtain the code referenced in this tutorial from SourceForge (one of the files entitled "datanucleus-samples-jdo-tutorial-*").
You can download DataNucleus in many ways, but the simplest is to download the distribution zip appropriate to your datastore (MongoDB in this case). You can do this from SourceForge DataNucleus download page. When you open the zip you will find DataNucleus jars in the lib directory, and dependency jars in the deps directory.
For our tutorial, say we have the following classes representing a store of products for sale.
So we have a relationship (Inventory having a set of Products), and inheritance (Product-Book). Now we need to be able to persist objects of all of these types, so we need to define persistence for them. There are many things that you can define when deciding how to persist objects of a type but the essential parts are
- Mark the class as PersistenceCapable so it is visible to the persistence mechanism
- Identify which field(s) represent the identity of the object (or use datastore-identity if no field meets this requirement).
So this is what we do now. Note that we could define persistence using XML metadata, annotations or via the JDO API. In this tutorial we will use annotations.
Note that we mark each class that can be persisted with @PersistenceCapable and their primary key field(s) with @PrimaryKey. In addition we defined a valueStrategy for Product field id so that it will have its values generated automatically. In this tutorial we are using application identity which means that all objects of these classes will have their identity defined by the primary key field(s). You can read more in datastore identity and application identity when designing your systems persistence.
Writing your own classes to be persisted is the start point, but you now need to define which objects of these classes are actually persisted. You do this via a file META-INF/persistence.xml at the root of the CLASSPATH. Like this
Note that you could equally use a properties file to define the persistence with JDO, but in this tutorial we use persistence.xml for convenience.
JDO relies on the classes that you want to persist implementing PersistenceCapable. You could write your classes manually to do this but this would be laborious. Alternatively you can use a post-processing step to compilation that "enhances" your compiled classes, adding on the necessary extra methods to make them PersistenceCapable. There are several ways to do this, most notably at post-compile, or at runtime. We use the post-compile step in this tutorial. DataNucleus JDO provides its own byte-code enhancer for instrumenting/enhancing your classes (in datanucleus-core) and this is included in the DataNucleus AccessPlatform zip file prerequisite.
To understand on how to invoke the enhancer you need to visualise where the various source and jdo files are stored
The first thing to do is compile your domain/model classes. You can do this in any way you wish, but the downloadable JAR provides an Ant task, and a Maven2 project to do this for you.
To enhance classes using the DataNucleus Enhancer, you need to invoke a command something like this from the root of your project.
This command enhances the .class files that have @PersistenceCapable annotations. If you accidentally omitted this step, at the point of running your application and trying to persist an object, you would get a ClassNotPersistenceCapableException thrown. The use of the enhancer is documented in more detail in the Enhancer Guide. The output of this step are a set of class files that representPersistenceCapable classes.
Writing your own classes to be persisted is the start point, but you now need to define which objects of these classes are actually persisted, and when. Interaction with the persistence framework of JDO is performed via a PersistenceManager. This provides methods for persisting of objects, removal of objects, querying for persisted objects, etc. This section gives examples of typical scenarios encountered in an application.
The initial step is to obtain access to a PersistenceManager, which you do as follows
Now that the application has a PersistenceManager it can persist objects. This is performed as follows
Note the following
- We have persisted the Inventory but since this referenced the Product then that is also persisted.
- The finally step is important to tidy up any connection to the datastore, and close the PersistenceManager
If you want to retrieve an object from persistent storage, something like this will give what you need. This uses a "Query", and retrieves all Product objects that have a price below 150.00, ordering them in ascending price order.
If you want to delete an object from persistence, you would perform an operation something like
Clearly you can perform a large range of operations on objects. We can't hope to show all of these here. Any good JDO book will provide many examples.
To run your JDO-enabled application will require a few things to be available in the Java CLASSPATH, these being
- Any persistence.xml file for the PersistenceManagerFactory creation
- Any JDO XML MetaData files for your persistable classes (not used in this example)
- MongoDB driver class needed for accessing your datastore
- The JDO API JAR (defining the JDO interface)
- The DataNucleus Core, DataNucleus JDO API and DataNucleus MongoDB JARs
After that it is simply a question of starting your application and all should be taken care of. You can access the DataNucleus Log file by specifying the logging configuration properties, and any messages from DataNucleus will be output in the normal way. The DataNucleus log is a very powerful way of finding problems since it can list all SQL actually sent to the datastore as well as many other parts of the persistence process.
In the above simple tutorial we showed how to employ JDO and persist objects to MongoDB. Obviously this just scratches the surface of what you can do, and to use JDO requires minimal work from the user. In this second part we show some further things that you are likely to want to do.
- Step 6 : Controlling the schema.
- Step 7 : Generate the database tables where your classes are to be persisted using SchemaTool.
In the above simple tutorial we didn't look at controlling the schema generated for these classes. Now let's pay more attention to this part by defining XML Metadata for the schema.
With JDO you have various options as far as where this XML MetaData files is placed in the file structure, and whether they refer to a single class, or multiple classes in a package. With the above example, we have both classes specified in the same file package-mongodb.orm, in the package these classes are in, since we want to persist to MongoDB.
This step is optional, depending on whether you have an existing database schema. If you haven't, at this point you can use the SchemaTool to generate the tables where these domain objects will be persisted. DataNucleus SchemaTool is a command line utility (it can be invoked from Maven2/Ant in a similar way to how the Enhancer is invoked). The first thing that you need is to update thepersistence.xml file with your database details.
Now we need to run DataNucleus SchemaTool. For our case above you would do something like this
This will generate the required tables, etc for the classes defined in the JDO Meta-Data file.