Learn Spring · 6/15

Data Persistence with Spring Data JPA

9 min read

Welcome, intrepid coder, to the fascinating world of persisting data with Spring Data JPA! Gone are the days of writing clunky, repetitive SQL queries in your Java code. Prepare to enter a realm where interacting with your database is as simple as calling a method.

But first, what problem are we even trying to solve? Imagine you're building a library application. You need to save information about books, authors, and borrowers. Without a proper framework, you'd be hand-crafting SQL statements for every single operation: inserting a new book, finding all books by a certain author, updating a book's status, and so on. This is not only tedious but also prone to errors (SQL injection, anyone? 😱).

This is where Spring Data JPA swoops in to save the day! It's a part of the larger Spring Data family and makes it incredibly easy to implement JPA (Java Persistence API) based repositories. In simpler terms, it provides a powerful and clean way to interact with your database, minimizing boilerplate code.

Let's embark on this journey to become data persistence wizards!

1. Connecting to the Database: DataSources and Connection Pools 🚪

Before we can do anything with our data, we need to establish a connection to our database. Think of it like plugging in a lamp; you need a power source.

The Problem: Opening and closing database connections for every single request is a very expensive operation. It's like hiring a new librarian every time someone wants to check out a book – highly inefficient!

The Solution: We use a DataSource and a Connection Pool.

  • DataSource: A DataSource is a factory for connections to the physical data source that it represents. It's a standard part of the JDBC specification and allows a container or framework to handle connection pooling and transaction management.
  • Connection Pool: Instead of creating a new connection every time, a connection pool maintains a cache of database connections that can be reused. This dramatically improves performance.

Funny Exaggeration: Not using a connection pool is like having a single, very flustered librarian who has to run to the main city archives (the database) every time a single person asks for a book, and then immediately forgets where the archives are. A connection pool is like having a set of pre-approved library cards, ready to be handed out.

Luckily for us, Spring Boot makes this incredibly simple. If you're using spring-boot-starter-data-jpa, it automatically includes and configures HikariCP, a high-performance JDBC connection pool.

Configuration (application.properties):

properties
# Database Connection Settings
spring.datasource.url=jdbc:mysql://localhost:3306/your_database
spring.datasource.username=your_username
spring.datasource.password=your_password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# HikariCP Settings (Optional - Spring Boot provides sensible defaults)
spring.datasource.hikari.maximum-pool-size=10
spring.datasource.hikari.minimum-idle=5
spring.datasource.hikari.idle-timeout=300000
spring.datasource.hikari.connection-timeout=20000

And that's it! Spring Boot takes care of the rest, providing you with a ready-to-use DataSource.

2. Mapping Entities to Tables: Core JPA Annotations (@Entity, @Id, @Column) 🗺️

Now that we have a connection, we need to tell Spring how our Java objects (which we'll call Entities) correspond to the tables in our database.

The Problem: How do we bridge the gap between our object-oriented Java world and the relational world of databases?

The Solution: We use JPA annotations to map our classes and their fields to tables and columns.

  • @Entity: This annotation marks a class as a JPA entity, signaling that it should be persisted in a database. By default, the table name will be the same as the class name.
  • @Id: This annotation designates a field as the primary key for the entity. Every entity must have a primary key.
  • @GeneratedValue: Often used with @Id, this specifies how the primary key is generated (e.g., auto-increment).
  • @Column: This annotation is used to specify the mapping between a field and a database column. You can customize properties like the column name, length, and whether it can be null.
  • @Table: If your table name is different from your class name, you can use this annotation to specify the correct table name.

Example: A Book Entity

Let's imagine a books table in our database with columns id, book_title, and author_name.

java
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Column;
import javax.persistence.Table;

@Entity
@Table(name = "books")
public class Book {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "book_title", nullable = false)
    private String title;

    @Column(name = "author_name")
    private String author;

    // Constructors, Getters, and Setters
}

With just these annotations, JPA now knows exactly how to store and retrieve Book objects from the books table. No SQL required!

3. The Magic of Spring Data Repositories (CrudRepository & JpaRepository) ✨

Here's where the real magic begins. Now that we have our entity mapped, how do we actually perform operations like saving, finding, and deleting books?

The Problem: Writing the implementation for basic CRUD (Create, Read, Update, Delete) operations for every entity is repetitive and boilerplate.

The Solution: Spring Data Repositories! You simply define an interface, and Spring Data JPA automatically creates an implementation at runtime.

You'll primarily be working with two main repository interfaces:

  • CrudRepository: Provides the fundamental CRUD operations.
  • JpaRepository: Extends CrudRepository and adds JPA-specific features like pagination, sorting, and batch operations.

Industry Standard: In most cases, you'll want to extend JpaRepository as it provides a more comprehensive set of features.

Creating a Repository:

java
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface BookRepository extends JpaRepository<Book, Long> {
    // That's it!
}

By extending JpaRepository<Book, Long>, our BookRepository now has methods like save(), findById(), findAll(), delete(), and many more, all implemented for us!

4. Defining Custom Queries: Method Name Derivation and the @Query Annotation ✍️

The built-in repository methods are great, but what if you need more specific queries? For instance, what if you want to find a book by its title?

The Problem: How do we create custom queries without writing a full implementation class?

The Solution: Spring Data JPA offers two powerful ways to do this:

a) Method Name Derivation

This is one of the most mind-blowing features of Spring Data JPA. You can define query methods simply by declaring their method signature in your repository interface. Spring Data will parse the method name and create the appropriate query for you.

The structure is find...By..., where you can use keywords like And, Or, Containing, StartingWith, etc.

Example:

In your BookRepository:

java
import java.util.List;

public interface BookRepository extends JpaRepository<Book, Long> {

    List<Book> findByTitle(String title);

    List<Book> findByAuthorContaining(String author);

    List<Book> findByTitleAndAuthor(String title, String author);
}

No implementation needed! Spring Data JPA understands these method names and generates the corresponding queries.

Interesting Fact: While you can chain many conditions, creating extremely long method names can become unreadable. For complex queries, the @Query annotation is a better choice.

b) The @Query Annotation

For more complex queries or when the method name derivation becomes too cumbersome, you can use the @Query annotation to define a custom query. You can write your query in either JPQL (Java Persistence Query Language) or native SQL.

JPQL Example:

java
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

public interface BookRepository extends JpaRepository<Book, Long> {

    @Query("SELECT b FROM Book b WHERE b.title = :title")
    List<Book> findBooksByTitle(@Param("title") String title);
}

Native SQL Example:

To use native SQL, you just need to set the nativeQuery attribute to true.

java
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

public interface BookRepository extends JpaRepository<Book, Long> {

    @Query(value = "SELECT * FROM books WHERE author_name = :author", nativeQuery = true)
    List<Book> findBooksByAuthor(@Param("author") String author);
}

The @Query annotation gives you full control over the query being executed.

5. Managing Entity Relationships: @OneToMany, @ManyToOne, and Fetch Types 🔗

Our library application isn't just about books; we also have authors. A single author can write many books, creating a relationship between them.

The Problem: How do we represent these relationships in our Java entities?

The Solution: JPA provides annotations for different types of relationships. Let's focus on the most common ones:

  • @ManyToOne: This is used on the "many" side of the relationship. For example, many Book entities can belong to one Author.
  • @OneToMany: This is used on the "one" side. One Author can have many Book entities.

Example:

Let's create an Author entity and link it with our Book entity.

Author Entity:

java
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.CascadeType;
import java.util.List;

@Entity
public class Author {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    @OneToMany(mappedBy = "author", cascade = CascadeType.ALL)
    private List<Book> books;

    // Getters and Setters
}

Updated Book Entity:

java
// ... other imports
import javax.persistence.ManyToOne;
import javax.persistence.JoinColumn;

@Entity
@Table(name = "books")
public class Book {

    // ... id and title fields

    @ManyToOne
    @JoinColumn(name = "author_id")
    private Author author;

    // ... rest of the class
}

Key Concepts:

  • mappedBy: In the @OneToMany annotation, mappedBy = "author" tells JPA that the author field in the Book entity is the owner of this relationship.
  • @JoinColumn: In the @ManyToOne annotation, this specifies the foreign key column in the books table that links to the author table.

Fetch Types: Eager vs. Lazy

When you fetch an Author, should you also immediately fetch all of their books? This is controlled by the fetch type.

  • FetchType.EAGER: Fetches the related entities along with the main entity in the same query. This is the default for @ManyToOne.
  • FetchType.LAZY: Fetches the related entities only when they are explicitly accessed. This is the default for @OneToMany.

The N+1 Problem: Imagine you fetch 10 authors, and for each author, you then access their list of books. If the books are lazily fetched, this will result in 1 query to get the authors, and then 10 more queries to get the books for each author (a total of 11 queries). This can be a major performance bottleneck!

Industry Standard: It's generally a good practice to default to FetchType.LAZY to avoid fetching unnecessary data and then use techniques like JOIN FETCH in your @Query annotations for specific use cases where you need the related data.


And there you have it! You've journeyed through the fundamentals of data persistence with Spring Data JPA. From connecting to the database to managing complex relationships, you now have the foundational knowledge to build robust and efficient data access layers in your Spring applications.

Remember: This is just the beginning. Spring Data JPA offers a wealth of other features like projections, specifications, and auditing to explore as you become more advanced. Happy coding! 🚀

📚 Further Reading and References

Challenge

You are tasked with modeling a simple library system using Spring Data JPA. Your goal is to create two entities, Author and Book, define their relationship, and create a repository interface for the Book entity with custom query methods.

Part 1: The Author Entity

  1. Create a class named Author.
  2. Mark it as a JPA entity that maps to a database table named authors.
  3. Define a primary key field named id of type Long with an auto-generated value strategy.
  4. Add a field named name of type String. This field must not be nullable and should map to a database column named author_name.
  5. Define a one-to-many relationship to the Book entity. An author can have many books. This relationship should be mapped by the author field in the Book class and must use lazy fetching.

Part 2: The Book Entity

  1. Create a class named Book.
  2. Mark it as a JPA entity.
  3. Define a primary key field named id of type Long with an auto-generated value strategy.
  4. Add a field named title of type String.
  5. Add a field named publicationYear of type Integer that maps to a database column named publication_year.
  6. Define a many-to-one relationship to the Author entity. This is the owning side of the relationship. The foreign key column in the database should be named author_id.

Part 3: The BookRepository

  1. Create an interface named BookRepository.
  2. This interface should extend JpaRepository, configured for the Book entity and its Long primary key.
  3. Add a custom query method using method name derivation to find all books published after a given year. The results should be ordered by the book's title in ascending order.
  4. Add another custom query method using the @Query annotation and JPQL to find all books written by an author with a specific name.

Expected result

Your final code should contain three completed parts: two classes (Author, Book) and one interface (BookRepository).

Author Class

  • Annotated with @Entity and @Table(name = "authors").
  • Contains an id field annotated with @Id and @GeneratedValue(strategy = GenerationType.IDENTITY).
  • Contains a name field annotated with @Column(name = "author_name", nullable = false).
  • Contains a List<Book> field named books annotated with @OneToMany(mappedBy = "author", fetch = FetchType.LAZY).

Book Class

  • Annotated with @Entity.
  • Contains an id field annotated with @Id and @GeneratedValue(strategy = GenerationType.IDENTITY).
  • Contains a title field of type String.
  • Contains a publicationYear field annotated with @Column(name = "publication_year").
  • Contains an Author field named author annotated with @ManyToOne and @JoinColumn(name = "author_id").

BookRepository Interface

  • The interface definition should be public interface BookRepository extends JpaRepository<Book, Long> { ... }.
  • It must include a method derived from its name, such as List<Book> findByPublicationYearGreaterThanOrderByTitleAsc(Integer year);.
  • It must include a method using JPQL, such as @Query("SELECT b FROM Book b JOIN b.author a WHERE a.name = :authorName") List<Book> findBooksByAuthorName(@Param("authorName") String authorName);.
java

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.