JPA and Hibernate - part 1

 The Java Persistence API (JPA) is a specification in Java for managing relational data in Java applications. It simplifies the interaction between Java objects and relational databases by providing an abstraction layer for Object-Relational Mapping (ORM). JPA enables developers to define how objects are persisted in a database using annotations or XML configurations.

JPA does not provide a concrete implementation. Instead, it relies on ORM frameworks like Hibernate, EclipseLink, and OpenJPA to implement its functionality.


Key Features of JPA

  1. Object-Relational Mapping (ORM): Maps Java objects to database tables and vice versa.
  2. Entity Management: Handles the lifecycle of entities such as creation, retrieval, update, and deletion.
  3. Query Language (JPQL): Provides a platform-independent query language.
  4. Transaction Management: Ensures data consistency and reliability.
  5. Annotations and Configurations: Simplifies mapping and database operations with annotations.

Entity Lifecycle

JPA entities have a lifecycle managed by the EntityManager. The lifecycle states are:

1. Transient: A new entity object is created but not yet associated with a persistence context.

2. Managed: The entity is associated with a persistence context, usually by being persisted or retrieved from the database.

3. Detached: An entity was once managed but is no longer associated with a persistence context.

4. Removed: An entity is marked for deletion.


Basic Annotations in JPA

Here are some commonly used JPA annotations:

1. Entity Mapping

  • @Entity: Marks a class as a JPA entity.
  • @Table: Specifies the table name (optional; defaults to class name).

2. Primary Key

  • @Id: Marks a field as the primary key.
  • @GeneratedValue: Specifies how the primary key is generated.

3. Column Mapping

  • @Column: Customizes the column name, length, nullable constraints, etc.
  • @Transient: Excludes a field from persistence.

4. Relationships

  • @OneToOne: Maps a one-to-one relationship.
  • @OneToMany: Maps a one-to-many relationship.
  • @ManyToOne: Maps a many-to-one relationship.
  • @ManyToMany: Maps a many-to-many relationship.

5. Lifecycle Callbacks

  • @PrePersist: Called before an entity is persisted.
  • @PostPersist: Called after an entity is persisted.
  • @PreRemove: Called before an entity is removed.
  • @PostRemove: Called after an entity is removed.
  • @PreUpdate: Called before an entity is updated.
  • @PostUpdate: Called after an entity is updated.

Comments