AI Hints
Home›Spring Boot Tutorial›Entities, Ids and Generated Values and Repositories
Spring Boot · Lesson 51 of 120

Repositories

Data access for free.

⏱ 2 min read▶ Video at 1:08:42🎓 Free
Watch this lesson in the Spring Boot courseWatch on YouTube ↗Full Spring Boot course

A repository is the object we use to save, find, and delete entities. And with Spring Data JPA, we don't even write it. We only declare it.

  • Save, find, delete
  • We don't write it
  • Just declare it

BookRepository.java

Book repository is just an interface. It extends Jpa Repository, with two types. Book is the entity, and Long is the type of its id. That's all. Spring writes the class for us, at startup.

BookRepository.javajava
public interface BookRepository extends JpaRepository<Book, Long> {
}

Methods you get for free

Save inserts, or updates, one entity. Find all returns every row. Find by id returns an Optional, that may be empty. Count counts the rows. And delete by id removes one.

MethodDoes
save(book)insert or update
findAll()all rows
findById(id)Optional<Book>
count()number of rows
deleteById(id)remove one

Using the repository

The runner receives the repository, by injection. Save all saves two books at once. Then we count, find by id, and check if an id exists. Run it. There are two books. Find by id two gives an Optional, holding Circe. Id nine gives an empty Optional, because it doesn't exist. And id one exists.

Loader.javajava
@Component
public class Loader implements CommandLineRunner {

    private final BookRepository books;

    public Loader(BookRepository books) {
        this.books = books;
    }

    @Override
    public void run(String... args) {
        books.saveAll(List.of(new Book("Dune", "Frank Herbert", 9.99),
                              new Book("Circe", "Madeline Miller", 10.99)));
        System.out.println("count: " + books.count());
        System.out.println("findById(2): " + books.findById(2L));
        System.out.println("findById(9): " + books.findById(9L));
        System.out.println("existsById(1): " + books.existsById(1L));
    }
}
Output
count: 2
findById(2): Optional[Book 2: Circe (10.99)]
findById(9): Optional.empty
existsById(1): true
Also uses Book.java
@Entity
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String title;
    private String author;
    private double price;

    protected Book() {}

    public Book(String title, String author, double price) {
        this.title = title; this.author = author; this.price = price;
    }

    public Long getId() { return id; }
    public String getTitle() { return title; }
    public String getAuthor() { return author; }
    public double getPrice() { return price; }
    public void setPrice(double price) { this.price = price; }

    @Override
    public String toString() { return "Book " + id + ": " + title + " (" + price + ")"; }
}
Also uses BookRepository.java
public interface BookRepository extends JpaRepository<Book, Long> {
}

Summary

Declare an interface that extends Jpa Repository, and Spring writes save, find, count, and delete for you. Next, a full CRUD API on the database.

Key takeaways
  • extends JpaRepository
  • <Book, Long>
  • Methods for free
Next up: CRUD with JpaRepository — the API, for real