Welcome to our comprehensive guide on JPA (Java Persistence API)! In this lesson, we'll cover everything you need to know about this powerful Java persistence technology. Let's dive in! šÆ
JPA (Java Persistence API) is a Java specification for persisting and managing Java objects (entities) to a relational database. It provides a simple and consistent way to access, store, and manipulate data in a database from Java applications.
To use JPA, you need to add some dependencies to your project. For Maven projects, add the following to your pom.xml:
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>javax.persistence-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.4.22.Final</version>
</dependency>For Gradle projects, add this to your build.gradle:
dependencies {
implementation 'javax.persistence:javax.persistence-api:2.2'
implementation 'org.hibernate:hibernate-entitymanager:5.4.22.Final'
}Entities are Java classes that map to database tables. Here's an example of a simple Employee entity:
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Employee {
@Id
private Long id;
private String name;
private String department;
// Getters and Setters
}š Note: The @Entity annotation marks a class as an entity. The @Id annotation indicates the primary key field.
The Persistence Context is a collection of managed Java objects (entities) that are currently being used by the application. To interact with the Persistence Context, you need an EntityManager. Here's an example of creating and using an EntityManager:
EntityManagerFactory factory = Persistence.createEntityManagerFactory("my-pu");
EntityManager entityManager = factory.createEntityManager();
// Use the entityManager here...
entityManager.close();
factory.close();To persist an entity, you first need to begin a transaction, then create the entity, and finally persist it using the EntityManager. Here's an example:
Employee employee = new Employee();
employee.setName("John Doe");
employee.setDepartment("IT");
EntityTransaction transaction = entityManager.getTransaction();
transaction.begin();
entityManager.persist(employee);
transaction.commit();To fetch an entity, you can use the find method of the EntityManager. Here's an example:
Employee employee = entityManager.find(Employee.class, 1L);What does JPA stand for?
What is the purpose of the `@Entity` annotation in JPA?
That's it for our introductory lesson on JPA! In the next lessons, we'll dive deeper into advanced topics like JPA queries, relationships, and more. Happy coding! š”