🎓 A1Learner
🔍
0 of 50 lessons completed

Repositories

A repository is an interface that talks to the database for one entity. An interface is a Java type that lists methods without their bodies.

One interface per entity

Task is the entity type. Long is the id type.

import org.springframework.data.jpa.repository.JpaRepository;

public interface TaskRepository extends JpaRepository<Task, Long> {
}

Keep the repository in a field

A controller keeps the repository in a field. The next lesson uses it to save.

private final TaskRepository tasks;

Example

import org.springframework.data.jpa.repository.JpaRepository;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

public interface TaskRepository extends JpaRepository<Task, Long> {

    static void main(String[] args) {
        System.out.println(TaskRepository.class.getInterfaces()[0].getSimpleName());
    }
}

@Entity
class Task {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String title;
    private boolean done;

    public Task() {
    }

    public Task(String title, boolean done) {
        this.title = title;
        this.done = done;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public boolean isDone() {
        return done;
    }

    public void setDone(boolean done) {
        this.done = done;
    }
}

Key points

  • A repository interface extends JpaRepository.
  • JpaRepository is a Spring Data type that works with one entity.
  • The interface names the entity type and the id type.
  • Spring makes the object that carries out the interface.
  • One repository serves one entity type.

In this example, the interface extends JpaRepository with Task and Long. The main method asks for the first parent type of the interface. The print shows JpaRepository. The Task class below is the entity the repository serves.

Note

The interface has no method bodies, and Spring fills them in.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does a repository interface extend?