Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Hunor Vadasz-Perhat
Hunor Vadasz-Perhat

Posted on

hibernate-001: @Entity

What Does@Entity Do in Depth?

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


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 classmust have ano-argument constructor (either implicitly or explicitly).
  • The classmust have at least one primary key defined with@Id or@IdClass.
  • The classmust not be final, and its persistent fields should not befinal ortransient.
  • The classshould 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 usefield-based orgetter-based access for persistence, depending on where@Id is placed.
    • If@Id is on afield, all fields are used for persistence (even without explicit@Column annotations).
    • If@Id is on agetter 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:

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

Example:

@EntitypublicclassPayment{...}
Enter fullscreen modeExit fullscreen mode
  • This maps to a table namedPayment (orPAYMENT, 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:

Paymentpayment=newPayment();// TransiententityManager.persist(payment);// Managed (Persistent)entityManager.detach(payment);// DetachedentityManager.remove(payment);// Removed
Enter fullscreen modeExit fullscreen mode

5. Integration with Hibernate

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

  • Automatic Table Creation (ifhibernate.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:

CREATETABLEpayments(customerNumberINTNOTNULL,checkNumberVARCHAR(50)NOTNULL,paymentDateDATENOTNULL,amountDECIMAL(10,2)NOTNULL,PRIMARYKEY(customerNumber,checkNumber));
Enter fullscreen modeExit fullscreen mode

6. Best Practices for Using@Entity

  • Alwaysdefine a primary key (@Id or@IdClass for composite keys).
  • Usemeaningful class names that represent real-world entities.
  • Implementequals() andhashCode() methodsbased on the primary key.
  • Useimmutable 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)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Software Engineer II @DXC Technology
  • Location
    Denmark
  • Joined

More fromHunor Vadasz-Perhat

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp