Step 3: Add a Main Class

In this step we will add a main class to the project to store and retrieve Point objects from the database:

  • Right click the tutorial package
    in the [Package Explorer] window and select New > Class.
  • The package name should be tutorial.
  • Enter Main as the class name (case sensitive).
  • Click Finish to create the class.

Copy and paste the following code to the newly created class file:

package tutorial;

import javax.persistence.*;
import java.util.*;

public class Main {
    public static void main(String[] args) {
        // Open a database connection
        // (create a new database if it doesn't exist yet):
        EntityManagerFactory emf =
            Persistence.createEntityManagerFactory(
                "$objectdb/db/p2.odb");
        EntityManager em = emf.createEntityManager();

        // Store 1000 Point objects in the database:
        em.getTransaction().begin();
        for (int i = 0; i < 1000; i++) {
            Point p = new Point(i, i);
            em.persist(p);
        }
        em.getTransaction().commit();

        // Find the number of Point objects in the database:
        Query q1 = em.createQuery("SELECT COUNT(p) FROM Point p");
        System.out.println("Total Points: " + q1.getSingleResult());

        // Find the average X value:
        Query q2 = em.createQuery("SELECT AVG(p.x) FROM Point p");
        System.out.println("Average X: " + q2.getSingleResult());

        // Retrieve all the Point objects from the database:
        TypedQuery<Point> query =
            em.createQuery("SELECT p FROM Point p", Point.class);
        List<Point> results = query.getResultList();
        for (Point p : results) {
            System.out.println(p);
        }

        // Close the database connection:
        em.close();
        emf.close();
    }
}

The main method creates an ObjectDB database file, stores 1000 Point objects in the database, and then runs a few queries, including a query that retrieves all 1000 Pointobjects from the database. In the end, it closes the database. A detailed explanation of the code can be found in the Quick Tour chapter of the ObjectDB Manual.

The next (and last) step in this tutorial is running the project.