AI Hints
Home›Spring Boot Tutorial›Counting and Exists, Transactions and Practice: Search Books
Spring Boot · Lesson 61 of 120

Counting and Exists

Quick questions.

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

Sometimes we don't need the books themselves. We just want to know how many there are, or whether one exists.

  • Not the books
  • How many?
  • Does it exist?

Count, exists, delete

Count by builds a count query, and returns a number. Exists by returns true or false. Both are faster than loading whole entities. And delete by removes every match, and needs a transaction, which we'll explain next.

keyvalue
countByAuthorhow many
existsByTitletrue / false
deleteByAuthorremove all matches
Fasterno entities loaded

The repository

Count by author counts an author's books. Exists by title checks for a title. Delete by author removes all their books, and returns how many it deleted. At Transactional is needed, because deleting changes data.

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

    long countByAuthor(String author);

    boolean existsByTitle(String title);

    @Transactional
    long deleteByAuthor(String author);
}

Quick answers

We count, check twice, delete, and count again. Run it. Jane Austen has two books. Emma exists, but Ulysses doesn't. Both Austen books are deleted. And six books are left.

QueryDemo.javajava
@Component
public class QueryDemo implements CommandLineRunner {

    private final BookRepository books;

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

    @Override
    public void run(String... args) {
        System.out.println("Austen books: " + books.countByAuthor("Jane Austen"));
        System.out.println("Have Emma? " + books.existsByTitle("Emma"));
        System.out.println("Have Ulysses? " + books.existsByTitle("Ulysses"));
        System.out.println("Deleted: " + books.deleteByAuthor("Jane Austen"));
        System.out.println("Books left: " + books.count());
    }
}
Output
Austen books: 2
Have Emma? true
Have Ulysses? false
Deleted: 2
Books left: 6
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> {

    long countByAuthor(String author);

    boolean existsByTitle(String title);

    @Transactional
    long deleteByAuthor(String author);
}
Also uses data.sql
INSERT INTO book (title, author, price) VALUES
  ('Dune', 'Frank Herbert', 9.99),
  ('The Hobbit', 'J.R.R. Tolkien', 8.99),
  ('Circe', 'Madeline Miller', 10.99),
  ('Children of Dune', 'Frank Herbert', 8.49),
  ('Song of Achilles', 'Madeline Miller', 9.49),
  ('The Fellowship of the Ring', 'J.R.R. Tolkien', 11.99),
  ('Emma', 'Jane Austen', 6.99),
  ('Persuasion', 'Jane Austen', 7.49);
Also uses application.properties
spring.jpa.defer-datasource-initialization=true

Summary

Count by, and exists by, answer quick questions, without loading entities. Delete by removes all matches, inside a transaction. Next, transactions.

Key takeaways
  • countBy...
  • existsBy...
  • deleteBy...
Next up: Transactions — all or nothing