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:
- x>Store structured data (like a spreadsheet, but smarter)
- x>Query it efficiently
- x>Enforce constraints and relationships
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:

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:

And use a Repository to interact with them:

With JPA and Spring Data, you get:
- x>Automatic table mapping
- x>Query generation from method names
- x>Cleaner, more maintainable code
Behind the Scenes
Under the hood, JPA still uses JDBC. It just hides the plumbing. JPA is powered by a provider like Hibernate, which:
- x>Maps your Java classes to database tables
- x>Handles SQL generation
- x>Manages the connection lifecycle
Quick Exercise
Try creating a basic Book entity:

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.