Step 3: Add a Main Class

In this step we will add a main class to the project from the database:


  • Open the [New Java Class] dialog box by right clicking the tutorial package node
    (in the [Package Explorer] window) and selecting New > Class.
  • The package name should be tutorial.
  • Enter Main as the class name - use exactly that class name.
  • Click Finish to create the new class.

Use copy and paste to fill the new source file with the following content:

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 =
        EntityManager em = emf.createEntityManager();

        // Store 1000 Point objects in the database:
        for (int i = 0; i < 1000; i++) {
            Point p = new Point(i, i);

        // 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) {

        // Close the database connection:

The main method creates an ObjectDB database file, storesis provided in the Quick Tour chapter of the ObjectDB Manual.

The next in this tutorial) is running the project.