This quick start guide will walk you through configuring a Spring Data JPA project using Maven. If you're new to Spring Data JPA, consider checking out our introductory guide first.
Key Takeaways
- Include the necessary Maven dependencies for Spring Data JPA in your
pom.xml. - Define JPA entities to model your database tables.
- Use Spring Data JPA repositories to simplify accessing data.
- Understand basic relationships such as one-to-one, one-to-many, and many-to-many in JPA.
Quick Start Using Maven
1) Including Maven Dependencies in pom.xml
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.1.0</version>
<relativePath/>
</parent>
<groupId>com.example</groupId>
<artifactId>spring-data-jpa-examples</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-data-jpa-examples</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
This setup includes dependencies necessary to work with Spring Data JPA:
- spring-boot-starter-data-jpa: Integrates Hibernate and the JPA specification.
- postgresql: A PostgreSQL connector for Java, used instead of MySQL for broader compatibility.
- spring-boot-starter-test: Facilitates testing Spring Boot applications.
2) Installing Maven Dependencies
Install the dependencies listed in your pom.xml with:
mvn clean install
Package the application into an executable JAR file using:
mvn package
3) Define Entities
Entities in JPA are classes you define that represent tables in your database. Let’s create Author and Book entities:
Author.java
package com.example.springdatajpaexamples;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
@Entity
public class Author {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToMany(mappedBy = "author")
private Set<Book> books = new HashSet<>();
public Long getId() { return id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Set<Book> getBooks() { return books; }
}
Book.java
package com.example.springdatajpaexamples;
import javax.persistence.*;
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
@ManyToOne
@JoinColumn(name = "author_id")
private Author author;
public Long getId() { return id; }
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public Author getAuthor() { return author; }
public void setAuthor(Author author) { this.author = author; }
}
These classes map directly to database tables, with @Entity marking them as JPA entities.
4) Add Repositories
Create repository interfaces for CRUD operations without boilerplate code:
AuthorRepository.java
package com.example.springdatajpaexamples;
import org.springframework.data.repository.CrudRepository;
public interface AuthorRepository extends CrudRepository<Author, Long> {
}
BookRepository.java
package com.example.springdatajpaexamples;
import org.springframework.data.repository.CrudRepository;
public interface BookRepository extends CrudRepository<Book, Long> {
}
These repositories leverage Spring Data to provide CRUD functionality without the need to define methods.
5) Configure application.properties
Your database connection and JPA settings go here:
spring.datasource.url=jdbc:postgresql://localhost:5432/example
spring.datasource.username=yourUsername
spring.datasource.password=yourPassword
spring.jpa.hibernate.ddl-auto=update
These properties configure the connection to a PostgreSQL database.
6) Run the Application
SpringDataJpaExamplesApplication.java
package com.example.springdatajpaexamples;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class SpringDataJpaExamplesApplication {
private static final Logger log = LoggerFactory.getLogger(SpringDataJpaExamplesApplication.class);
public static void main(String[] args) {
SpringApplication.run(SpringDataJpaExamplesApplication.class, args);
}
@Bean
public CommandLineRunner demo(AuthorRepository authorRepo, BookRepository bookRepo) {
return (args) -> {
Author author = new Author();
author.setName("Sam Erickson");
authorRepo.save(author);
authorRepo.findById(author.getId()).ifPresent(a -> log.info("Found author: " + a.getName()));
};
}
}
Use CommandLineRunner to test your entity classes once the application starts.
Spring Data JPA Examples
Join Relationships
By using annotations like @OneToOne, @OneToMany, and @ManyToOne, you can express different types of relationships mapped to your database:
@OneToOne
For one-to-one relationships between Books and Authors, adjust your entity definitions as follows:
Author.java
package com.example.springdatajpaexamples;
import javax.persistence.*;
@Entity
public class Author {
// Existing code...
@OneToOne
private Book book;
public Book getBook() { return book; }
public void setBook(Book book) { this.book = book; }
}
Book.java
package com.example.springdatajpaexamples;
import javax.persistence.*;
@Entity
public class Book {
// Existing code...
@OneToOne(mappedBy = "book")
private Author author;
public Author getAuthor() { return author; }
public void setAuthor(Author author) { this.author = author; }
}
@OneToMany
To configure one-to-many relationships, where an author can have multiple books:
Author.java
package com.example.springdatajpaexamples;
import javax.persistence.*;
@Entity
public class Author {
// Existing code...
@OneToMany(mappedBy = "author")
private Set<Book> books = new HashSet<>();
public Set<Book> getBooks() { return books; }
}
Book.java
package com.example.springdatajpaexamples;
import javax.persistence.*;
@Entity
public class Book {
// Existing code...
@ManyToOne
@JoinColumn(name = "author_id")
private Author author;
public Author getAuthor() { return author; }
public void setAuthor(Author author) { this.author = author; }
}
@ManyToMany
For many-to-many relationships, where books can have many authors and vice versa:
Author.java
package com.example.springdatajpaexamples;
import javax.persistence.*;
@Entity
public class Author {
// Existing code...
@ManyToMany(mappedBy = "authors")
private Set<Book> books = new HashSet<>();
public Set<Book> getBooks() { return books; }
}
Book.java
package com.example.springdatajpaexamples;
import javax.persistence.*;
@Entity
public class Book {
// Existing code...
@ManyToMany
@JoinTable(
name = "book_author",
joinColumns = @JoinColumn(name = "book_id"),
inverseJoinColumns = @JoinColumn(name = "author_id")
)
private Set<Author> authors = new HashSet<>();
public Set<Author> getAuthors() { return authors; }
}
These configuration details map entities to multiple relationships within the database.
FAQ
What is the function of the @Entity annotation in JPA?
The @Entity annotation specifies that the class is an entity and is mapped to a database table.
How do I configure connection pooling in Spring Data JPA with PostgreSQL?
Connection pooling can be configured in application.properties by setting properties for a specific datasource, such as HikariCP, which is the default connection pool implementation in Spring Boot.
Do I always need a repository class for every entity?
It's common practice to create a repository for aggregates in your domain model, but you don't need a repository for every single entity. Repositories are crucial for managing collections of entities and accessing the database.
