Stop 13 · Databases, JDBC & JPATopics · 10/12

JPA & Hibernate

Part of the Java Roadmap

In short

Writing JDBC for every table means pages of boring mapping code. JPA lets you work with plain Java objects and generates most of the SQL, which is how nearly every Spring Boot app talks to its database.

JPA is the standard Java API for mapping objects to database tables, and Hibernate is its most common implementation. You annotate classes with @Entity and the ORM generates SQL.

The jaadu sits between two people at a meeting table, turning to each in turn and translating with expressive hand gestures, one side holding a coffee cup and the other a filing cabinet drawer.

Think of it like this

The translator at the meeting

A Japanese client visits your office in Hyderabad. You speak English, the client speaks Japanese, and a translator turns every sentence into the other language. You think in Java objects, the database speaks SQL, and Hibernate is the translator. JPA is the job description that says what any translator must be able to do.

Watch it happen

From persist() to a row in the table

new Student()
Persistence context
Generated SQL
Table row

1/5You create a Student object. It is just a plain object, not yet tracked.

The big ideas

What you need to know

JPA is a spec

Jakarta Persistence (package jakarta.persistence) defines annotations and EntityManager. Hibernate implements it.

@Entity and @Id

@Entity maps a class to a table. @Id marks the primary key; @GeneratedValue lets the database create it.

Persistence context

Managed entities are tracked. Changes are written automatically at commit. This is called dirty checking.

JPQL

Queries are written against entities and fields, like SELECT s FROM Student s WHERE s.city = :city.

See it in code

Walk through the code

java
1import jakarta.persistence.*;2 3@Entity4@Table(name = "students")5public class Student {6    @Id7    @GeneratedValue(strategy = GenerationType.IDENTITY)8    private Long id;9 10    @Column(nullable = false, length = 100)11    private String name;12 13    private String city;14 15    protected Student() {}            // JPA needs a no-arg constructor16 17    public Student(String name, String city) {18        this.name = name;19        this.city = city;20    }21 22    public Long getId() { return id; }23    public String getCity() { return city; }24    public void setCity(String city) { this.city = city; }25}26 27// Using it with a plain EntityManager28em.getTransaction().begin();29Student s = new Student("Ananya", "Kochi");30em.persist(s);31s.setCity("Pune");                    // becomes an UPDATE automatically32em.getTransaction().commit();33 34List<Student> puneStudents = em.createQuery(35        "SELECT s FROM Student s WHERE s.city = :city", Student.class)36    .setParameter("city", "Pune")37    .getResultList();

1/5This class maps to the students table.

Spring Boot creates the EntityManager and transactions for you. The mapping annotations stay exactly the same.

Save yourself the pain

Common mistakes

Oops

Importing javax.persistence in a Spring Boot 3 project.

Do this instead

Spring Boot 3 uses Jakarta EE, so import jakarta.persistence.*.

Oops

Using spring.jpa.hibernate.ddl-auto=update in production.

Do this instead

Let a migration tool like Flyway own the schema. Use validate in production.

Oops

Writing JPQL with table and column names.

Do this instead

JPQL uses class and field names. Use a native query only when you really need database-specific SQL.

Your mission

Map your first entity

~30 min

Quick check

You load a managed entity, call a setter and the transaction commits. What happens?

Go deeper

  1. 1Map an entity with @Entity, @Id and @GeneratedValue.
  2. 2Save, find, update and delete an entity through an EntityManager.
  3. 3Enable SQL logging and read the queries Hibernate runs for you.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge