Java.Hibernate.What is an entity in Hibernate?

What is an entity in Hibernate?

Answer:
In Hibernate (and JPA), an entity is a lightweight, persistent Java object whose state is mapped to a table row in a relational database. Entities represent the domain model of your application and are the primary building blocks for Object-Relational Mapping.

🔹 Key points about entities:
✅ An entity must be a POJO (Plain Old Java Object).
✅ It must be annotated with @Entity (or mapped via XML in legacy Hibernate).
✅ It must have a field annotated with @Id to define the primary key.
✅ By default, the entity class name is mapped to a table with the same name — or you can customize it using @Table.

🔹 Basic example of a Hibernate entity:

import javax.persistence.*;

@Entity
@Table(name = "users")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "username")
    private String username;

    private String email;

    // Getters and setters
}

🔹 What makes an entity special:

  • Hibernate automatically tracks its state changes inside a session.
  • Changes to entities are synchronized with the database (e.g., on flush or transaction commit).
  • Supports features like lazy loading, cascading, and automatic SQL generation.

🔹 Entity lifecycle states:

  • Transient: Not associated with any Hibernate session.
  • Persistent: Associated with an open session and synchronized with the DB.
  • Detached: Was persistent but the session was closed or the object was evicted.

Key takeaway:
An entity is a persistent Java object mapped to a database table row, central to ORM and Hibernate’s ability to manage your data automatically.

This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.