Introduction to Spring Data JPA
Introduction
Welcome to the first lesson of the course, "Persisting Data with Spring Data JPA." Throughout this course, you'll learn how to leverage Spring Data JPA to connect your application to relational databases, create simple and complex relations, implement pagination and sorting, and more. In this introductory lesson, we’ll explore the low-level way of working with relational databases using JDBC and contrast it with the high-level, more efficient way using JPA. We'll also introduce Spring Data JPA, a Spring module that simplifies database operations by building on top of JPA. Let's get started!
Understanding JDBC
Java Database Connectivity (JDBC) is a Java Standard Edition (SE) API that allows Java applications to interact with relational databases. It involves writing explicit SQL queries, managing database connections, and handling result sets manually. Here is an example of how to retrieve data using JDBC:
As you can see, this approach is cumbersome with a lot of boilerplate code. This method has nothing to do with Spring Boot and reflects the complexities involved in manual database operations.
If you want to dive deeper into JDBC, refer to the official specification.
Simplifying Database Access with JPA
The Java Persistence API (JPA) is a Java Enterprise Edition (EE) specification for Object Relational Mapping (ORM), which simplifies database interactions by mapping Java objects to database tables. ORM allows you to manipulate database records through Java objects, making your code cleaner and more maintainable. Here’s an example of a JPA entity class:
In this example:
@Entity: Marks this class as a JPA entity. This annotation will map the class to a database table namedperson(default naming convention).@Id: Specifies the primary key of the entity. This annotation maps theidfield to the primary key column of thepersontable.@GeneratedValue(strategy = GenerationType.IDENTITY): Defines how the primary key is generated. UsingIDENTITYstrategy, theidfield will be auto-incremented by the database.
So, this class will be mapped to a table named person, which will have columns id, name, and age, with id being the primary key.
For more information on JPA, consult the official specification.
