1. Overview

The Java Data Objects is an API designed to persist object-oriented data into any database and provide a user-friendly query language using Java syntax.

In this article, we are going to see how to use the JDO API to persist our objects in a database.

2. Maven Dependencies and Setup

We are going to use DataNucleus JDO API, which offers full support for the JDO 3.2 API and is up to date.

Let’s add the following dependency to our pom.xml file:

<dependency>
    <groupId>org.datanucleus</groupId>
    <artifactId>javax.jdo</artifactId>
    <version>3.2.1</version>
</dependency>
<dependency>
    <groupId>org.datanucleus</groupId>
    <artifactId>datanucleus-core</artifactId>
    <version>6.0.6</version>
</dependency>
<dependency>
    <groupId>org.datanucleus</groupId>
    <artifactId>datanucleus-api-jdo</artifactId>
    <version>6.0.1</version>
</dependency>
<dependency>
    <groupId>org.datanucleus</groupId>
    <artifactId>datanucleus-rdbms</artifactId>
    <version>6.0.6</version>
</dependency>

The latest versions of the dependencies can be found here: javax.jdo, datanucleus-core, datanucleus-api-jdo and datanucleus-rdbms.

3. Model

We are going to save our data in a database, and before we can do that, we need to create a class that JDO will use to store our data.

To do that, we need to create a class with some properties and annotate it with the @PersistentCapable:

@PersistenceCapable
public class Product {
 
    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.INCREMENT)
    long id;
 
    String name;
    Double price = 0.0;

    // standard constructors, getters, setters
}

We also annotated our primary key and the chosen strategy.

Once we create our object, we need to run the enhancer to generate the bytecode required by JDO. Using Maven, we can run this command:

mvn datanucleus:enhance

This step is mandatory. Otherwise, we get a compile time error that the class is not enhanced.

Of course, it’s possible to do this automatically during a Maven build:

<plugin>
    <groupId>org.datanucleus</groupId>
    <artifactId>datanucleus-maven-plugin</artifactId>
    <version>6.0.0-release</version>
    <configuration>
        <api>JDO</api>
        <props>${basedir}/datanucleus.properties</props>
        <log4jConfiguration>${basedir}/log4j.properties</log4jConfiguration>
        <verbose>true</verbose>
    </configuration>
    <executions>
        <execution>
            <phase>process-classes</phase>
            <goals>
                <goal>enhance</goal>
            </goals>
        </execution>
    </executions>
</plugin>

The latest version of the plugin can be found here: datanucleus-maven-plugin

4. Persisting Objects

We get access to the database using a JDO factory that gives us the transaction manager that is in charge of performing transactions:

PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null);
PersistenceManager pm = pmf.getPersistenceManager();

Transactions are used to allow a rollback in case of an error:

Transaction tx = pm.currentTransaction();

We make our transactions inside a try/catch block:

Product product = new Product("Tablet", 80.0);
pm.makePersistent(product);

In our finally block, we define these operations to be done in the case of a failure.

If, for any reason, the transaction cannot be completed, we make a rollback, and we also close the connection to the database with pm.close():

finally {
    if (tx.isActive()) {
        tx.rollback();
    }
    pm.close();
}

To connect our program to the database, we need to create a persistence-unit at runtime to specify the persistent classes, the database type, and connection parameters:

PersistenceUnitMetaData pumd = new PersistenceUnitMetaData(
  "dynamic-unit", "RESOURCE_LOCAL", null);
pumd.addClassName("com.baeldung.jdo.Product");
pumd.setExcludeUnlistedClasses();
pumd.addProperty("javax.jdo.option.ConnectionDriverName", "org.h2.Driver");
pumd
  .addProperty("javax.jdo.option.ConnectionURL", "jdbc:h2:mem:mypersistence");
pumd.addProperty("javax.jdo.option.ConnectionUserName", "sa");
pumd.addProperty("javax.jdo.option.ConnectionPassword", "");
pumd.addProperty("datanucleus.autoCreateSchema", "true");

5. Reading Objects

To read data from our database inside our transaction block, we create a query. Then, we store these items in a Java List collection, which will hold an in-memory copy of the information from the persistent storage.

The persistence manager gives us access to the query interface that allows us to interact with the database:

Query q = pm.newQuery(
  "SELECT FROM " + Product.class.getName() + " WHERE price < 1");
List<Product> products = (List<Product>) q.execute();
Iterator<Product> iter = products.iterator();
while (iter.hasNext()) {
    Product p = iter.next();
    // show the product information
}

6. Updating Objects

To update objects in the database, we need to find the objects that we want to update using a query, then we update the results of the query and commit the transaction:

Query query = pm.newQuery(Product.class, "name == \"Phone\"");
Collection result = (Collection) query.execute();
Product product = (Product) result.iterator().next();
product.setName("Android Phone");

7. Deleting Objects

Similar to the update procedure, we search for the object first and then delete it using the persistence manager. In those situations, JDO updates the persistent storage:

Query query = pm.newQuery(Product.class, "name == \"Android Phone\"");
Collection result = (Collection) query.execute();
Product product = (Product) result.iterator().next();
pm.deletePersistent(product);

8. XML Datastores

Using the XML plugin, we can use XML files to persist our data.

We specify our ConnectionURL, indicating that it is an XML file and specifying the name of the file:

pumdXML.addProperty("javax.jdo.option.ConnectionURL", "xml:file:myPersistence.xml");

An XML datastore does not support the auto-increment property, so we need to create another class:

@PersistenceCapable()
public class ProductXML {

    @XmlAttribute
    private long productNumber = 0;
    @PrimaryKey
    private String name = null;
    private Double price = 0.0;
 
    // standard getters and setters

The @XmlAttribute annotation denotes that this will appear in the XML file as an attribute of the element.

Let’s create and persist our product:

ProductXML productXML = new ProductXML(0,"Tablet", 80.0);
pm.makePersistent(productXML);

We get the product stored in the XML file:

<productXML productNumber="0">
    <name>Tablet</name>
    <price>80.0</price>
</productXML>

8.1. Recover Objects from the XML Datastore

We can recover our objects from the XML file using a query:

Query q = pm.newQuery("SELECT FROM " + ProductXML.class.getName());
List<ProductXML> products = (List<ProductXML>) q.execute();

And then, we use the iterator to interact with each object.

9. JDO Queries

JDOQL is an object-based query language designed to perform queries using Java objects.

9.1. Declarative JDOQL

Using the declarative query, we declare the parameters and set them using Java; this ensures type safety:

Query qDJDOQL = pm.newQuery(Product.class);
qDJDOQL.setFilter("name == 'Tablet' && price == price_value");
qDJDOQL.declareParameters("double price_value");
List<Product> resultsqDJDOQL = qDJDOQL.setParameters(80.0).executeList();

9.2. SQL

JDO provides a mechanism for executing standard SQL queries:

Query query = pm.newQuery("javax.jdo.query.SQL", "SELECT * FROM PRODUCT");
query.setClass(Product.class);
List<Product> results = query.executeList();

We use javax.jdo.query.SQL as one parameter for the query object, and the second parameter is the SQL itself.

9.3. JPQL

JDO provides a mechanism for executing JPA queries as well. We can use the full syntax of the JPA query language:

Query q = pm.newQuery("JPQL",
  "SELECT p FROM " + Product.class.getName() + " p WHERE p.name = 'Laptop'");
List results = (List) q.execute();

10. Summary

In this tutorial, we:

  • created a simple CRUD application that uses JDO
  • to save and retrieve our data as XML
  • examined common query mechanisms

As always, you can find the code from the article over on GitHub.

Course – LSD (cat=Persistence)

Get started with Spring Data JPA through the reference Learn Spring Data JPA course:

>> CHECK OUT THE COURSE
res – Persistence (eBook) (cat=Persistence)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.