Databases and Persistence: JDBC and JPA

Welcome to one of the most career-critical chapters: connecting your Java app to a database. This is how your app remembers things after you close it. No more just printing stuff to the screen—we're building real-world, persistent systems.

What is Persistence?

Persistence means saving data beyond the life of the program — storing it on disk so it can be reloaded later. A database helps us:

JDBC: Java Database Connectivity

JDBC is the low-level API that lets Java talk directly to relational databases like MySQL, PostgreSQL, or H2. Here’s what basic JDBC code looks like:

JDBC Example

Downside: It’s very verbose. You write everything — SQL queries, connection management, mapping rows to objects.

Enter JPA: Java Persistence API

JPA is a higher-level abstraction over JDBC. It lets you work with Java objects, not raw SQL. You define classes that represent database tables:

JPA Example

And use a Repository to interact with them:

JPA Repository Example

With JPA and Spring Data, you get:

Behind the Scenes

Under the hood, JPA still uses JDBC. It just hides the plumbing. JPA is powered by a provider like Hibernate, which:

Quick Exercise

Try creating a basic Book entity:

Book Entity Example

Then think about:

What table would this become in the database?
What columns would it have?
How would you query for books with a certain title?

(We’ll wire this up with Spring Data JPA soon!)

What’s Next

You now know how to persist data — but where does all this logic belong? Next, we’ll explore project architecture: organizing code into layers like controllers, services, and repositories to keep it clean and scalable. Get ready to architect like a pro.