Defining a JPA Entity Class
To store Point objects in a database using JPA, you must define an entity class. A JPA entity class is a POJO (Plain Old Java Object), an ordinary Java class that is marked (annotated) to indicate that it can represent objects in the database. Conceptually, this is similar to serializable classes, which are marked to indicate that they can be serialized.
The Point entity class
The following Point class represents points in a plane. It is marked as an entity class, which enables you to store and retrieve Point objects from the database:
package com.objectdb.tutorial; import jakarta.persistence.Entity; @Entityjakarta.persistence.EntityDeclares that the annotated class is an entity. public class Point { // Persistent Fields: private int x; private int y; // Constructor: Point (int x, int y) { this.x = x; this.y = y; } // Accessor Methods: public int getX() { return this.x; } public int getY() { return this.y; } // String Representation: @Override public String toString() { return String.format("(%d, %d)", this.x, this.y); } }
As the example shows, an entity class is an ordinary Java class. The only JPA-specific addition is the @Entityjakarta.persistence.EntityDeclares that the annotated class is an entity. annotation, which marks the class as an entity class.
If you try to persist Point objects without marking the Point class as an entity, JPA throws a PersistenceExceptionjakarta.persistence.PersistenceExceptionThrown by the persistence provider when a problem occurs.. This behavior is similar to the NotSerializableException that Java throws when you try to serialize a non-serializable object. However, all JPA exceptions are unchecked, whereas Java I/O exceptions are checked.
Persistent fields in entity classes
When you store an entity in the database, its methods and code are not stored. Only the persistent state of the object, which is represented by its persistent fields, is stored. By default, any field that is not declared as static or transient is a persistent field. For example, the persistent fields of the Point entity class are x and y, which represent the point's position in a plane. The values of these fields are stored in the database when an entity is persisted.
Chapter 2 provides more information about defining entity classes, including which types to use for persistent fields, how to define and use a primary key, and how to define and use a version field.
If you are familiar with JPA, you might have noticed that the Point entity class has no primary key (@Idjakarta.persistence.IdIdentifies the primary key of an entity.) field. As an object database, ObjectDB supports implicit object IDs, so an explicit primary key is not required. However, ObjectDB also supports explicit JPA primary keys, including composite primary keys and automatic sequential value generation. This powerful feature of ObjectDB is absent from other object-oriented databases.