What is JPA (Java Persistence API)?
sobes.tech AI
Answer from AI
JPA is a specification API for managing data persistence in Java applications. It provides a standard way to map Java objects to relational databases (or other data stores) and back. JPA is part of the Java EE platform (now Jakarta EE) and can also be used in standalone applications.
Key components of JPA:
- Entity: Ordinary Java classes (POJOs) annotated with
@Entity, representing data in the database. - EntityManager: Interface for interacting with the persistence context. Used for finding, creating, updating, and deleting entities.
- Persistence Context: A set of entities managed by
EntityManager. Changes to entities are tracked here before synchronization with the database. - JPQL (Java Persistence Query Language): An object-oriented query language similar to SQL but operates on entities and their relationships instead of tables and columns.
- Criteria API: An object-oriented API for executing dynamic queries.
persistence.xml: Configuration file describing persistence units and their properties (e.g., database connection info, mapping strategies).
JPA is not a specific ORM (Object-Relational Mapping) implementation but defines contracts and APIs. Various JPA providers implement this specification, the most popular of which are:
- Hibernate
- EclipseLink
- Apache OpenJPA
Example of defining an entity:
// Entity representing a record in the `products` table
@Entity
// Name of the table in the database
@Table(name = "products")
public class Product {
// Primary key
@Id
// Strategy for primary key generation
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
// `name` column in the table
private String name;
// `price` column in the table
private BigDecimal price;
// Constructors, getters, and setters
// ...
}
Example of using EntityManager:
// Obtaining EntityManager from EntityManagerFactory
EntityManagerFactory emf = Persistence.createEntityManagerFactory("myPersistenceUnit");
EntityManager em = emf.createEntityManager();
try {
// Begin transaction
em.getTransaction().begin();
// Create a new entity
Product newProduct = new Product();
newProduct.setName("Laptop");
newProduct.setPrice(new BigDecimal("1200.00"));
// Save entity to the database
em.persist(newProduct);
// Find entity by primary key
Product foundProduct = em.find(Product.class, 1L);
System.out.println("Found product: " + foundProduct.getName());
// Execute JPQL query
List<Product> allProducts = em.createQuery("SELECT p FROM Product p", Product.class).getResultList();
for (Product p : allProducts) {
System.out.println(p.getName());
}
// Commit transaction
em.getTransaction().commit();
} catch (Exception e) {
// Rollback transaction in case of error
if (em.getTransaction().isActive()) {
em.getTransaction().rollback();
}
e.printStackTrace();
} finally {
// Close EntityManager
em.close();
// Close EntityManagerFactory
emf.close();
}
The main goal of JPA is to simplify the development of applications working with databases by abstracting low-level JDBC and SQL details, providing an object-oriented approach to persistence. This increases code portability and reduces its dependency on a specific database.