Creating Your First JPA Entity and Repository in Spring Boot

This post links to: Building a Spring Boot CRUD App With Postgres from Scratch: The Complete Guide.

This guide follows on from Setting Up Spring Boot and PostgreSQL. Detailed below is how to create a database entity and repository using JPA to interact with a Postgres database using Java.

A Guide to JPA

JPA stands for Java Persistence API. It is a Java specification to simplify interacting with relational databases. JPA defines how you can map Java objects (classes) to relational database tables. So instead of using SQL to interact with the database, you use Java objects.

Why Use JPA?

JPA vs Hibernate

In Java terms, think of JPA as the interface and Hibernate as the implementation.

You use JPA annotations and interfaces and under the hood Spring Boot configures Hibernate to make it work.

Spring Boot Starter Data JPA

The spring-boot-starter-data-jpa library is what Spring Boot uses to implement JPA and Hibernate.

A Spring Boot starter is a pre-configured bundle of dependencies designed to achieve a specific goal within a Spring application. In our case, connecting our Spring application to a relational database (PostgreSQL).

Here are the dependencies that the spring-boot-starter-data-jpa library brings in:

spring-starter-jpa-deps.png

Creating a JPA Entity

We can create a JPA entity called User simply like so:

// User.java
@Entity
@Table(name = "users")
public class User {

    @Id
    @GeneratedValue
    @Column(name = "id")
    private Long id;

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

    @Column(name = "email")
    private String email;

    public User(final Long id, final String name, final String email) {

        this.id = id;
        this.name = name;
        this.email = email;
    }

    public User() {}

    public Long getId() {

        return id;
    }

    public String getName() {

        return name;
    }

    public void setName(final String name) {

        this.name = name;
    }

    public String getEmail() {

        return email;
    }

    public void setEmail(final String email) {

        this.email = email;
    }
}

Annotations

Creating a JPA Repository

Now we have a JPA entity defined, we need to create a JPA repository to interact with the database for our entity.

Here's how to create a JPA repository for our entity:

// UserRepository.java
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}

So Spring Boot autoconfigures:

Creating this repository gives us access to many methods to interact with the database, including:

Testing Our JPA Setup

We can now test whether our JPA/Hibernate setup will work creating a @DataJpaTest test.

@DataJpaTest will bring the JPA and Hibernate context up in your Spring Boot application and also bring in a H2 in memory database to use as a test database.

To use H2 for tests, you'll need to add the following dependency to the build.gradle file:

// build.gradle
dependencies {
//  other deps... 
    testRuntimeOnly 'com.h2database:h2'
}

Then define the following test below:

// UserRepositoryTest.java
@DataJpaTest
class UserRepositoryTest {

    @Autowired private UserRepository userRepository;

    @Test
    void userRepositoryTest() {

        final var user = new User(null, "fbd", "fbd@example.com");
        final var savedUser = userRepository.save(user);

        final var foundUserList = userRepository.findAll();

        assertThat(foundUserList).hasSize(1);
        assertThat(foundUserList.get(0)).isEqualTo(savedUser);
    }
}

You can run the test in the command line using Gradle:

./gradlew test --tests 'UserRepositoryTest'

What's Next?

So to recap we:

GitHub Example

Up Next: Building Your First REST API with Spring Boot