523 words
Step 3: Add a Main Class
In this step we will add a main class to the project with code that will store Point objects in the database and then retrieve them 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 case sensitive 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 = Persistence.createEntityManagerFactory("$objectdb/db/points.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 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.