Java JPA Basics: Entities, EntityManager and JPQL
Java JPA (Jakarta Persistence API) is the standard way to save and load Java objects in a relational database without writing most of the SQL yourself. You mark a class as an entity, and JPA maps its fields to table columns, generates INSERT, UPDATE and SELECT statements, and turns result rows back into objects.
JPA removes the repetitive JDBC code you wrote in the previous lessons: setting parameters one by one, reading each column from a ResultSet, and building objects by hand. In this lesson you will set up a JPA project, map your first entity, save, find, update and delete objects with the EntityManager, understand entity lifecycle states, and query data with JPQL.
What Is JPA in Java?
JPA is a specification: a set of interfaces and annotations in the jakarta.persistence package. On its own it does nothing. A provider (also called an implementation) does the actual work of talking to the database.
| Name | What it is |
|---|---|
| Jakarta Persistence (JPA) | The standard API: @Entity, EntityManager, JPQL, ... |
| Hibernate ORM | The most popular JPA provider, also used by Spring Boot |
| EclipseLink | The reference JPA provider |
| JDBC | The lower layer every provider uses to run SQL |
Your code imports only jakarta.persistence types, so in principle you can switch providers without changing it. This lesson uses Hibernate as the provider.
Note: Before 2020 the package was
javax.persistence. When Java EE moved to the Eclipse Foundation and became Jakarta EE, the package was renamed tojakarta.persistence. Old tutorials usingjavax.persistencewill not compile against current Hibernate versions.
Core JPA Concepts
| Concept | Meaning |
|---|---|
| Entity | A class annotated with @Entity; each object is one row in a table |
| Persistence unit | A named configuration (database URL, entity classes, settings), usually in persistence.xml |
EntityManagerFactory | Created once per persistence unit; heavy, thread-safe, lives for the whole application |
EntityManager | Light, not thread-safe; used for one unit of work, then closed |
| Persistence context | The set of entity objects an EntityManager is currently tracking |
EntityTransaction | Begins, commits or rolls back a transaction when running outside a server |
| JPQL | Jakarta Persistence Query Language: SQL-like queries written against entities and fields, not tables and columns |
Setting Up a Java JPA Project
You need a JPA provider and a JDBC driver. Hibernate brings the jakarta.persistence-api jar with it. The examples use the in-memory H2 database.
<dependencies>
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-core</artifactId>
<version>7.4.0.Final</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>2.3.232</version>
</dependency>
</dependencies>
The project layout looks like this:
src/main/java/com/gocourse/jpa/Student.java
src/main/java/com/gocourse/jpa/SaveStudents.java
src/main/resources/META-INF/persistence.xml
The persistence unit is defined in src/main/resources/META-INF/persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="https://jakarta.ee/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/persistence https://jakarta.ee/xml/ns/persistence/persistence_3_2.xsd"
version="3.2">
<persistence-unit name="school">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.gocourse.jpa.Student</class>
<properties>
<property name="jakarta.persistence.jdbc.url" value="jdbc:h2:mem:school;DB_CLOSE_DELAY=-1"/>
<property name="jakarta.persistence.jdbc.user" value="sa"/>
<property name="jakarta.persistence.jdbc.password" value=""/>
<property name="jakarta.persistence.schema-generation.database.action" value="drop-and-create"/>
</properties>
</persistence-unit>
</persistence>
How it works:
name="school"is the name your code uses to create theEntityManagerFactory.<class>lists the entity classes JPA should manage.- The
jakarta.persistence.jdbc.*properties are standard and work with any provider. drop-and-createmakes JPA generate the tables from your entities at startup. It is handy for learning and tests; real applications manage the schema with migration tools such as Flyway or Liquibase instead.
Note: Hibernate needs Java 17 or newer. It also prints INFO log lines at startup. The outputs in this lesson show only what the programs print with
System.out.
Your First JPA Entity
An entity is a normal Java class with a few annotations. JPA needs an @Id field and a no-argument constructor (it may be protected).
package com.gocourse.jpa;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
@Entity
@Table(name = "students")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, length = 40)
private String name;
@Column(nullable = false, unique = true, length = 60)
private String email;
private int marks;
protected Student() {
// required by JPA, which creates objects through this constructor
}
public Student(String name, String email, int marks) {
this.name = name;
this.email = email;
this.marks = marks;
}
public Long getId() { return id; }
public String getName() { return name; }
public String getEmail() { return email; }
public int getMarks() { return marks; }
public void setMarks(int marks) { this.marks = marks; }
@Override
public String toString() {
return "Student{id=" + id + ", name=" + name + ", marks=" + marks + "}";
}
}
The table JPA generates from this class looks like:
students
+----+-------+-------------------+-------+
| id | name | email | marks |
+----+-------+-------------------+-------+
How it works:
@Entitytells JPA to manage this class.@Table(name = "students")sets the table name; without it the table would be calledStudent.@Idmarks the primary key, and@GeneratedValue(strategy = GenerationType.IDENTITY)lets the database assign it (an auto-increment column).@Columncustomizes a column:nullable = falseaddsNOT NULL,unique = trueadds a unique constraint,lengthsets theVARCHARsize.- Fields without annotations, such as
marks, are still mapped, using the field name as the column name.
| Annotation | Purpose |
|---|---|
@Entity | Marks a class as a persistent entity |
@Table | Sets the table name and other table options |
@Id | Marks the primary key field |
@GeneratedValue | Lets the database or provider generate key values |
@Column | Sets column name, length, nullability and uniqueness |
@Transient | Excludes a field from the table |
Saving Objects with persist()
To save a new object, open an EntityManager, start a transaction, call persist(), and commit.
package com.gocourse.jpa;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
public class SaveStudents {
public static void main(String[] args) {
try (EntityManagerFactory factory = Persistence.createEntityManagerFactory("school");
EntityManager entityManager = factory.createEntityManager()) {
Student asha = new Student("Asha", "asha@example.com", 88);
Student ravi = new Student("Ravi", "ravi@example.com", 72);
Student meena = new Student("Meena", "meena@example.com", 92);
System.out.println("Id before persist: " + asha.getId());
entityManager.getTransaction().begin();
entityManager.persist(asha);
entityManager.persist(ravi);
entityManager.persist(meena);
entityManager.getTransaction().commit();
System.out.println("Saved: " + asha);
System.out.println("Saved: " + ravi);
System.out.println("Saved: " + meena);
}
}
}
Output:
Id before persist: null
Saved: Student{id=1, name=Asha, marks=88}
Saved: Student{id=2, name=Ravi, marks=72}
Saved: Student{id=3, name=Meena, marks=92}
How it works:
Persistence.createEntityManagerFactory("school")readspersistence.xml, connects to H2 and creates thestudentstable.persist()makes each object managed. WithIDENTITYkeys, JPA runs theINSERTright away so it can read back the generated id, which it writes into the object'sidfield.commit()makes the inserts permanent. BothEntityManagerFactoryandEntityManagerareAutoCloseablein current JPA, so try-with-resources closes them.
Finding an Entity by Primary Key
find() loads one entity by its id. It returns null when no row has that id.
package com.gocourse.jpa;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
public class FindStudent {
public static void main(String[] args) {
try (EntityManagerFactory factory = Persistence.createEntityManagerFactory("school")) {
try (EntityManager entityManager = factory.createEntityManager()) {
entityManager.getTransaction().begin();
entityManager.persist(new Student("Asha", "asha@example.com", 88));
entityManager.persist(new Student("Ravi", "ravi@example.com", 72));
entityManager.getTransaction().commit();
}
try (EntityManager entityManager = factory.createEntityManager()) {
Student found = entityManager.find(Student.class, 2L);
System.out.println("Found: " + found);
System.out.println("Email: " + found.getEmail());
Student missing = entityManager.find(Student.class, 99L);
System.out.println("Id 99: " + missing);
Student again = entityManager.find(Student.class, 2L);
System.out.println("Same object on second find: " + (found == again));
}
}
}
}
Output:
Found: Student{id=2, name=Ravi, marks=72}
Email: ravi@example.com
Id 99: null
Same object on second find: true
How it works:
- The second
EntityManagerstarts with an empty persistence context, so the firstfind()runs aSELECTand builds aStudentfrom the row. - The key must match the type of the
@Idfield. The id is aLong, so the code passes2L. - The second
find()for id 2 does not touch the database. The persistence context already holds that entity, so it returns the same object. This is often called the first-level cache.
Updating Data with Dirty Checking
There is no update() method in JPA. You change a managed entity with its setters, and at commit JPA compares it with the state it loaded and writes an UPDATE for whatever changed. This is called dirty checking.
package com.gocourse.jpa;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
public class UpdateStudent {
public static void main(String[] args) {
try (EntityManagerFactory factory = Persistence.createEntityManagerFactory("school")) {
try (EntityManager entityManager = factory.createEntityManager()) {
entityManager.getTransaction().begin();
entityManager.persist(new Student("Ravi", "ravi@example.com", 72));
entityManager.getTransaction().commit();
}
try (EntityManager entityManager = factory.createEntityManager()) {
entityManager.getTransaction().begin();
Student ravi = entityManager.find(Student.class, 1L);
ravi.setMarks(ravi.getMarks() + 8); // only a setter call, no SQL
entityManager.getTransaction().commit(); // UPDATE happens here
}
try (EntityManager entityManager = factory.createEntityManager()) {
System.out.println("After update: " + entityManager.find(Student.class, 1L));
}
}
}
}
Output:
After update: Student{id=1, name=Ravi, marks=80}
How it works:
find()returns a managedStudent, and JPA remembers a snapshot of its original values.setMarks()only changes the Java object. Atcommit(), JPA notices thatmarksdiffers from the snapshot and runsUPDATE students SET ... WHERE id = 1.- The third
EntityManagerreads the row fresh from the database, proving the change was saved.
Deleting Data with remove()
remove() deletes a managed entity. The DELETE runs at commit.
package com.gocourse.jpa;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
public class DeleteStudent {
public static void main(String[] args) {
try (EntityManagerFactory factory = Persistence.createEntityManagerFactory("school");
EntityManager entityManager = factory.createEntityManager()) {
entityManager.getTransaction().begin();
entityManager.persist(new Student("Kavin", "kavin@example.com", 64));
entityManager.getTransaction().commit();
entityManager.getTransaction().begin();
Student kavin = entityManager.find(Student.class, 1L);
entityManager.remove(kavin);
entityManager.getTransaction().commit();
System.out.println("After remove: " + entityManager.find(Student.class, 1L));
}
}
}
Output:
After remove: null
How it works:
remove()only works on a managed entity, so the code first loads Kavin withfind().- After the commit the row is gone, and
find()returnsnull.
JPA Entity Lifecycle States
Every entity object is in one of four states. Knowing the state tells you whether your changes will be saved.
| State | Meaning | How it gets there |
|---|---|---|
| New (transient) | Plain Java object; JPA does not know it | new Student(...) |
| Managed | Tracked by an EntityManager; changes are saved at commit | persist(), find(), query results, merge() result |
| Detached | Has an id, but its EntityManager is closed or it was detached | close(), clear(), detach() |
| Removed | Scheduled for deletion at commit | remove() |
contains() tells you whether an object is managed by a given EntityManager.
package com.gocourse.jpa;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
public class LifecycleStates {
public static void main(String[] args) {
try (EntityManagerFactory factory = Persistence.createEntityManagerFactory("school");
EntityManager entityManager = factory.createEntityManager()) {
Student asha = new Student("Asha", "asha@example.com", 88);
System.out.println("New - managed? " + entityManager.contains(asha));
entityManager.getTransaction().begin();
entityManager.persist(asha);
System.out.println("After persist - managed? " + entityManager.contains(asha));
entityManager.getTransaction().commit();
entityManager.detach(asha);
System.out.println("After detach - managed? " + entityManager.contains(asha));
asha.setMarks(95); // not tracked: asha is detached
entityManager.getTransaction().begin();
Student managedCopy = entityManager.merge(asha); // copies asha's state into a managed instance
System.out.println("merge result managed? " + entityManager.contains(managedCopy)
+ ", same object as asha? " + (managedCopy == asha));
entityManager.getTransaction().commit();
entityManager.getTransaction().begin();
entityManager.remove(managedCopy);
System.out.println("After remove - managed? " + entityManager.contains(managedCopy));
entityManager.getTransaction().commit();
}
}
}
Output:
New - managed? false
After persist - managed? true
After detach - managed? false
merge result managed? true, same object as asha? false
After remove - managed? false
How it works:
- A new object is unknown to JPA until
persist(). detach()stops tracking, sosetMarks(95)alone would never reach the database.merge()does not attach the detached object itself. It loads (or reuses) a managed instance with the same id, copies the detached object's values into it, and returns that managed copy. The new marks are saved at commit.remove()moves the managed copy to the removed state, and the row is deleted at commit.
Note: A common bug is changing a detached object and expecting it to be saved. Always keep using the object returned by
merge(), not the one you passed in.
Querying Data with JPQL
JPQL looks like SQL but works with entity names and field names. You write Student and s.marks, not students and the column name, and JPA translates it into SQL for your database.
package com.gocourse.jpa;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import jakarta.persistence.TypedQuery;
import java.util.List;
public class JpqlQueries {
public static void main(String[] args) {
try (EntityManagerFactory factory = Persistence.createEntityManagerFactory("school");
EntityManager entityManager = factory.createEntityManager()) {
entityManager.getTransaction().begin();
entityManager.persist(new Student("Asha", "asha@example.com", 88));
entityManager.persist(new Student("Ravi", "ravi@example.com", 72));
entityManager.persist(new Student("Meena", "meena@example.com", 92));
entityManager.persist(new Student("Kavin", "kavin@example.com", 64));
entityManager.getTransaction().commit();
// 1. Filtered and sorted list with a named parameter
TypedQuery<Student> topQuery = entityManager.createQuery(
"SELECT s FROM Student s WHERE s.marks >= :minMarks ORDER BY s.marks DESC", Student.class);
topQuery.setParameter("minMarks", 80);
List<Student> topStudents = topQuery.getResultList();
System.out.println("Marks >= 80:");
topStudents.forEach(student -> System.out.println(" " + student.getName() + " " + student.getMarks()));
// 2. A single value
Long total = entityManager.createQuery("SELECT COUNT(s) FROM Student s", Long.class)
.getSingleResult();
Double average = entityManager.createQuery("SELECT AVG(s.marks) FROM Student s", Double.class)
.getSingleResult();
System.out.println("Total students: " + total + ", average: " + average);
// 3. Selecting one field with LIKE
List<String> names = entityManager.createQuery(
"SELECT s.name FROM Student s WHERE s.email LIKE :pattern ORDER BY s.name", String.class)
.setParameter("pattern", "%a%@example.com")
.getResultList();
System.out.println("Emails with 'a' before @: " + names);
}
}
}
Output:
Marks >= 80:
Meena 92
Asha 88
Total students: 4, average: 79.0
Emails with 'a' before @: [Asha, Kavin, Meena, Ravi]
How it works:
createQuery(jpql, Student.class)returns aTypedQuery<Student>, sogetResultList()gives aList<Student>with no casting.:minMarksis a named parameter, filled withsetParameter(). LikePreparedStatementplaceholders, parameters keep you safe from SQL injection.COUNTreturns aLongandAVGreturns aDouble.getSingleResult()returns exactly one value. The average is(88 + 72 + 92 + 64) / 4 = 79.0.- You can select a single field (
s.name) instead of the whole entity. All four email addresses contain anabefore the@, so all four names come back, sorted.
Note: Never build JPQL by string concatenation with user input, such as
"... WHERE s.name = '" + input + "'". Use parameters, for the same reasons explained in Java PreparedStatement.
Real-World Example: A Student Service with JPA
Real code wraps JPA calls in a service class. Each method is one unit of work: it gets an EntityManager, runs inside a transaction and returns plain results. Jakarta Persistence 3.2 adds runInTransaction() and callInTransaction() to the factory, which create the EntityManager, begin, commit (or roll back on an exception) and close for you.
package com.gocourse.jpa;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import java.util.List;
public class StudentServiceApp {
static class StudentService {
private final EntityManagerFactory factory;
StudentService(EntityManagerFactory factory) {
this.factory = factory;
}
Long enroll(String name, String email, int marks) {
if (marks < 0 || marks > 100) {
throw new IllegalArgumentException("Marks must be 0-100, got " + marks);
}
return factory.callInTransaction(entityManager -> {
Student student = new Student(name, email, marks);
entityManager.persist(student);
return student.getId();
});
}
void addBonus(Long studentId, int bonus) {
factory.runInTransaction(entityManager -> {
Student student = entityManager.find(Student.class, studentId);
if (student == null) {
throw new IllegalArgumentException("No student with id " + studentId);
}
student.setMarks(Math.min(100, student.getMarks() + bonus)); // saved by dirty checking
});
}
List<Student> rankAbove(int minMarks) {
return factory.callInTransaction(entityManager -> entityManager
.createQuery("SELECT s FROM Student s WHERE s.marks >= :min ORDER BY s.marks DESC, s.name", Student.class)
.setParameter("min", minMarks)
.getResultList());
}
boolean withdraw(Long studentId) {
return factory.callInTransaction(entityManager -> {
Student student = entityManager.find(Student.class, studentId);
if (student == null) {
return false;
}
entityManager.remove(student);
return true;
});
}
}
public static void main(String[] args) {
try (EntityManagerFactory factory = Persistence.createEntityManagerFactory("school")) {
StudentService service = new StudentService(factory);
Long ashaId = service.enroll("Asha", "asha@example.com", 88);
Long raviId = service.enroll("Ravi", "ravi@example.com", 72);
Long meenaId = service.enroll("Meena", "meena@example.com", 92);
Long kavinId = service.enroll("Kavin", "kavin@example.com", 64);
System.out.println("Enrolled ids: " + List.of(ashaId, raviId, meenaId, kavinId));
try {
service.enroll("Divya", "divya@example.com", 120);
} catch (IllegalArgumentException e) {
System.out.println("Rejected: " + e.getMessage());
}
service.addBonus(raviId, 10);
service.addBonus(meenaId, 10); // capped at 100
System.out.println("Withdrew Kavin: " + service.withdraw(kavinId));
System.out.println("Withdrew id 99: " + service.withdraw(99L));
System.out.println("Students with 80 or more:");
for (Student student : service.rankAbove(80)) {
System.out.println(" " + student.getName() + " - " + student.getMarks());
}
}
}
}
Output:
Enrolled ids: [1, 2, 3, 4]
Rejected: Marks must be 0-100, got 120
Withdrew Kavin: true
Withdrew id 99: false
Students with 80 or more:
Meena - 100
Asha - 88
Ravi - 82
How it works:
- One factory, many short units of work. The
EntityManagerFactoryis created once inmainand passed to the service. Each method gets its own short-livedEntityManagerthroughrunInTransaction()orcallInTransaction(). - Validation before the database.
enroll()rejects Divya's marks of 120 in Java, so nothing is written. - Updates through dirty checking.
addBonus()only callssetMarks(). Ravi goes from 72 to 82; Meena would reach 102 butMath.mincaps her at 100. - Automatic rollback. If a lambda throws, for example when
addBonus()gets an unknown id, the transaction is rolled back before the exception reaches the caller. - JPQL for reports.
rankAbove(80)returns Meena, Asha and Ravi, sorted by marks and then name. Kavin was withdrawn, so he no longer appears.
Under the hood every one of these calls still borrows a JDBC connection, which is why the Java connection pooling lesson matters even when you use JPA, and why commit and rollback follow the same rules as in Java JDBC Transactions. The next lesson looks at Hibernate itself, the provider behind these examples, and its own native API.