ObjectDB ObjectDB

Step 3: Add a Main Class

In this step we will add code to the Main class (that was generated with the project) in order to store Point objects in the database and then retrieve them from the database.

Use copy and paste to replace the content of the Main class 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, stores 1000 Point objects in the database, and then run a few queries, including a query that retrieves all the 1000 Point objects from the database. Finally it closes the database. A detailed explanation of the code is provided in the Quick Tour chapter of the ObjectDB Manual.

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