DEV Community

Hunor Vadasz-Perhat
Hunor Vadasz-Perhat

Posted on

hibernate-001: @Entity

What Does @Entity Do in Depth?

The @Entity annotation in Java's Jakarta Persistence API (JPA) (formerly Java Persistence API) is used to define a persistent entity—a class that represents a table in a relational database. When this annotation is applied to a class, it marks the class as an entity bean that can be mapped to a database table by an Object-Relational Mapping (ORM) framework such as Hibernate.


1. Core Functionality of @Entity

The @Entity annotation:

  1. Marks a Java class as a JPA entity—indicating that instances of this class will be stored in the database.
  2. Instructs the ORM framework to map the class to a table—each instance corresponds to a row in the table.
  3. Works with the persistence provider (e.g., Hibernate) to manage lifecycle operations such as persisting, retrieving, updating, and deleting records.

2. Key Rules and Behavior of @Entity

  • The class must have a no-argument constructor (either implicitly or explicitly).
  • The class must have at least one primary key defined with @Id or @IdClass.
  • The class must not be final, and its persistent fields should not be final or transient.
  • The class should not be an interface or an abstract class (though abstract entities are possible with inheritance strategies).
  • Field Access Strategy: The JPA provider determines if it should use field-based or getter-based access for persistence, depending on where @Id is placed.
    • If @Id is on a field, all fields are used for persistence (even without explicit @Column annotations).
    • If @Id is on a getter method, then JPA persists the properties through their getter methods.

3. Default Table Mapping and Customization

By default, if you annotate a class with @Entity without specifying a table name, the ORM provider assumes:

  • The table name is the same as the entity class name (case-sensitive depending on the database).
  • The table schema is determined by the database defaults.

Example:

@Entity
public class Payment { ... }
Enter fullscreen mode Exit fullscreen mode
  • This maps to a table named Payment (or PAYMENT, depending on the database).
  • To specify a different table name, use @Table(name = "payments").

4. Lifecycle of an @Entity

JPA entities exist in different states:

  1. Transient: The entity is instantiated but not yet associated with any persistence context.
  2. Managed (Persistent): The entity is associated with a persistence context, meaning JPA tracks its changes.
  3. Detached: The entity was once managed but is no longer in a persistence context.
  4. Removed: The entity is marked for deletion and will be deleted upon transaction commit.

Example:

Payment payment = new Payment();  // Transient
entityManager.persist(payment);   // Managed (Persistent)
entityManager.detach(payment);    // Detached
entityManager.remove(payment);    // Removed
Enter fullscreen mode Exit fullscreen mode

5. Integration with Hibernate

If Hibernate is the JPA provider, @Entity enables features such as:

  • Automatic Table Creation (if hibernate.hbm2ddl.auto=create is set).
  • Lazy Loading and Eager Fetching of relationships.
  • Dirty Checking (tracking changes and persisting only modified fields).

Hibernate will generate a table like:

CREATE TABLE payments (
    customerNumber INT NOT NULL,
    checkNumber VARCHAR(50) NOT NULL,
    paymentDate DATE NOT NULL,
    amount DECIMAL(10,2) NOT NULL,
    PRIMARY KEY (customerNumber, checkNumber)
);
Enter fullscreen mode Exit fullscreen mode

6. Best Practices for Using @Entity

  • Always define a primary key (@Id or @IdClass for composite keys).
  • Use meaningful class names that represent real-world entities.
  • Implement equals() and hashCode() methods based on the primary key.
  • Use immutable fields where applicable, but ensure JPA can still construct an instance.

Conclusion

The @Entity annotation is the backbone of JPA's ORM mechanism. It transforms Java objects into database rows and integrates them with the persistence context. Combined with other JPA annotations (@Table, @Id, @Column), it allows fine-grained control over database interactions while keeping object-oriented design principles intact.

Top comments (0)