Skip to content
Spring Boot

Spring

Spring Boot

Spring

Java Persistence API(JPA)

admin, March 15, 2025

JPA (Java Persistence API) is a specification for managing relational data in Java applications. It provides an abstraction over SQL-based databases, making it easier to work with data using object-oriented concepts. Here’s a quick breakdown of key JPA concepts:

Key Components of JPA

  1. Entity – A Java class mapped to a database table.
  2. Persistence Context – The cache where entity instances are managed.
  3. Entity Manager – The core interface for interacting with the database.
  4. JPQL (Java Persistence Query Language) – A query language similar to SQL but works with entity objects.
  5. Annotations – Used for mapping Java classes to database tables.

Example of JPA in Action

1. Define an Entity

import jakarta.persistence.*;

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

@Column(nullable = false)
private String brand;

@Column(nullable = false)
private String model;

// Getters and Setters
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }

public String getBrand() { return brand; }
public void setBrand(String brand) { this.brand = brand; }

public String getModel() { return model; }
public void setModel(String model) { this.model = model; }
}

2. Use an EntityManager to Persist Data

import jakarta.persistence.*;

public class CarRepository {
private static final EntityManagerFactory emf = Persistence.createEntityManagerFactory("my-persistence-unit");

public void saveCar(Car car) {
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
em.persist(car);
em.getTransaction().commit();
em.close();
}
}

3. Query Data Using JPQL

public List<Car> getCarsByBrand(String brand) {
EntityManager em = emf.createEntityManager();
List<Car> cars = em.createQuery("SELECT c FROM Car c WHERE c.brand = :brand", Car.class)
.setParameter("brand", brand)
.getResultList();
em.close();
return cars;
}

Additional Features

  • Relationships: JPA supports @OneToOne, @OneToMany, @ManyToOne, and @ManyToMany relationships.
  • Cascade Operations: Control how changes in one entity affect related entities.
  • Criteria API: Type-safe queries instead of JPQL.
Spring Boot

Post navigation

Previous post
Next post

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

©2025 Spring Boot | WordPress Theme by SuperbThemes