JPA and Hibernate - Persist Data

 

Setting Up the Environment

Prerequisites

  1. JDK 11 or later.
  2. Maven or Gradle as the build tool.
  3. A database (e.g., MySQL, PostgreSQL, or H2 for testing).

Dependencies

Add the following dependencies to your pom.xml for Maven:

<dependencies>

<!-- JPA API -->

<dependency>

<groupId>jakarta.persistence</groupId>

<artifactId>jakarta.persistence-api</artifactId>

<version>3.1.0</version>

</dependency>


<!-- Hibernate JPA Implementation -->

<dependency>

<groupId>org.hibernate</groupId>

<artifactId>hibernate-core</artifactId>

<version>6.3.0.Final</version>

</dependency>


<!-- Postgresql Driver -->

<dependency>

<groupId>org.postgresql</groupId>

<artifactId>postgresql</artifactId>

<version>42.5.0</version>

</dependency>

</dependencies>


JPA Configuration

Persistence Configuration

Create a file named persistence.xml in src/main/resources/META-INF/:

<persistence xmlns="https://jakarta.ee/xml/ns/persistence"

version="3.0">

<persistence-unit name="my-pu">

<!-- JPA Provider -->

<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>


<!-- Database Connection -->

<properties>

<property name="jakarta.persistence.jdbc.url" value="jdbc:postgresql://localhost:5432/postgres"/>

<property name="jakarta.persistence.jdbc.user" value="postgres"/>

<property name="jakarta.persistence.jdbc.password" value="root"/>


<!-- Hibernate Settings -->

<property name="hibernate.hbm2ddl.auto" value="update"/>

<property name="hibernate.show_sql" value="true"/>

<property name="hibernate.format_sql" value="true"/>

</properties>

</persistence-unit>

</persistence>


Creating a JPA Entity

Employee Entity

This entity represents a table employees in the database.

package edu.raj.learn;


import jakarta.persistence.*;


@Entity

@Table(name = "employees")

public class Employee {


@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

private Long id;


@Column(name = "full_name", nullable = false, length = 100)

private String name;


@Column(name = "dept", nullable = false)

private String department;


@Transient

private String tempField; // Not persisted in the database


// Lifecycle Callback

@PrePersist

public void onPrePersist() {

System.out.println("Before persisting: " + this.name);

}


// Default constructor

public Employee() {}


// Constructor with parameters

public Employee(String name, String department) {

this.name = name;

this.department = department;

}


// Getters and Setters

public Long getId() {

return id;

}


public void setId(Long id) {

this.id = id;

}


public String getName() {

return name;

}


public void setName(String name) {

this.name = name;

}


public String getDepartment() {

return department;

}


public void setDepartment(String department) {

this.department = department;

}

}




Main driver class for testing persist method

public class YourApplication {


public static void main(String[] args) {

// Create EntityManagerFactory and EntityManager

EntityManagerFactory emf = Persistence.createEntityManagerFactory("my-pu");

EntityManager em = emf.createEntityManager();


// Start a transaction

em.getTransaction().begin();


// Create and persist a new entity

Employee emp1 = new Employee("Alice", "HR");

em.persist(emp1);


// Commit transaction

em.getTransaction().commit();



// Close the EntityManager

em.close();

emf.close();

}

}



  1. 1. Creating an EntityManagerFactory and EntityManager:

    EntityManagerFactory emf = Persistence.createEntityManagerFactory("my-pu"); EntityManager em = emf.createEntityManager();
    • EntityManagerFactory is responsible for creating EntityManager instances. It is a heavyweight object, and it's typically created once at the start of an application.
    • Persistence.createEntityManagerFactory("my-pu") uses a persistence unit name ("my-pu") to load configuration details (like database connection settings) from a persistence.xml file.
    • EntityManager is the primary JPA interface used to interact with the database. It allows operations like querying, persisting, and removing entities.

    2. Starting a Transaction:

    em.getTransaction().begin();
    • JPA requires that any changes to the database (e.g., inserting, updating, or deleting entities) occur within a transaction.
    • begin() starts a new transaction, which ensures that database operations can be rolled back or committed atomically.

    3. Creating and Persisting a New Entity:

    Employee emp1 = new Employee("Alice", "HR"); em.persist(emp1);
    • A new Employee entity is created with the name "Alice" and the department "HR".
    • em.persist(emp1) tells the EntityManager to manage this entity and save it to the database. The entity is in the "managed" state now and will be written to the database when the transaction is committed.

    4. Committing the Transaction:

    em.getTransaction().commit();
    • The transaction is committed, meaning that the changes (in this case, persisting the Employee entity) are saved permanently to the database.
    • If there were any issues, a rollback could be performed instead, but here we are assuming everything goes as planned.

    5. Closing the EntityManager and EntityManagerFactory:

    em.close(); emf.close();
    • After the transaction is complete, the EntityManager and EntityManagerFactory should be closed to free up resources.
    • em.close() releases the resources associated with the EntityManager, and emf.close() closes the factory and releases its resources.

Comments