AI Hints
Home›Spring Boot Tutorial›Project: The Plan, Entities, Repositories and Service
Spring Boot · Lesson 114 of 120

Project: Repositories and Service

Queries and logic.

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

With the data model ready, we need a repository, for the queries. And a service, for the business logic.

  • The data model is ready
  • A repository
  • A service

BookRepository.java

Book Repository gets all the CRUD methods from Jpa Repository. We add one derived query, to search by author. Containing, and ignore case, make the search friendly.

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

    List<Book> findByAuthorContainingIgnoreCase(String author);
}

This runner searches twice, with different letter cases. Run it. Lower case tolkien finds both Tolkien books. And upper case MILLER finds both Miller books.

RepoCheck.javajava
@Component
public class RepoCheck implements CommandLineRunner {

    private final BookRepository books;

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

    @Override
    public void run(String... args) {
        books.findByAuthorContainingIgnoreCase("tolkien")
             .forEach(b -> System.out.println(b.getTitle()));
        books.findByAuthorContainingIgnoreCase("MILLER")
             .forEach(b -> System.out.println(b.getTitle()));
    }
}
Output
INFO  BookshopApplication : Started BookshopApplication in 2.294 seconds
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 setTitle(String title) { this.title = title; }
    public void setAuthor(String author) { this.author = author; }
    public void setPrice(double price) { this.price = price; }
}
Also uses BookRepository.java
public interface BookRepository extends JpaRepository<Book, Long> {

    List<Book> findByAuthorContainingIgnoreCase(String author);
}
Also uses CreateBook.java
public record CreateBook(
    @NotBlank String title,
    @NotBlank String author,
    @Positive double price
) {}
Also uses BookResponse.java
public record BookResponse(Long id, String title, String author, double price) {

    static BookResponse from(Book b) {
        return new BookResponse(b.getId(), b.getTitle(), b.getAuthor(), b.getPrice());
    }
}
Also uses NewPrice.java
public record NewPrice(@Positive double price) {}
Also uses BookNotFoundException.java
@ResponseStatus(HttpStatus.NOT_FOUND)
public class BookNotFoundException extends RuntimeException {
    public BookNotFoundException(long id) { super("Book " + id + " was not found"); }
}
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

BookService, part one

The service is transactional. Search returns every book, or only those by an author, as responses. And by id returns one book.

BookService.javajava
@Service
@Transactional
public class BookService {

    private final BookRepository books;

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

    @Transactional(readOnly = true)
    public List<BookResponse> search(String author) {
        List<Book> found = author == null ? books.findAll()
                                          : books.findByAuthorContainingIgnoreCase(author);
        return found.stream().map(BookResponse::from).toList();
    }

    @Transactional(readOnly = true)
    public BookResponse byId(long id) { return BookResponse.from(find(id)); }
    ...
}

BookService, part two

Create saves a new book. Change price loads a book, and sets the price. There's no save call, the transaction saves the change. Delete removes a book. And find throws not found, when the id doesn't exist.

BookController.javajava
    ...
    public BookResponse create(CreateBook req) {
        Book saved = books.save(new Book(req.title(), req.author(), req.price()));
        return BookResponse.from(saved);
    }

    public BookResponse changePrice(long id, double price) {
        Book book = find(id);
        book.setPrice(price);
        return BookResponse.from(book);
    }

    public void delete(long id) { books.delete(find(id)); }

    private Book find(long id) {
        return books.findById(id).orElseThrow(() -> new BookNotFoundException(id));
    }
}

Trying the service

This runner calls each service method. Run it. Austen's two books come back as responses. Emma now costs five ninety nine. After one delete, seven books are left. And book ninety nine was not found.

ServiceDemo.javajava
@Component
public class ServiceDemo implements CommandLineRunner {

    private final BookService service;

    public ServiceDemo(BookService service) { this.service = service; }

    @Override
    public void run(String... args) {
        service.search("austen").forEach(System.out::println);
        System.out.println(service.changePrice(7, 5.99));
        service.delete(8);
        System.out.println("Books left: " + service.search(null).size());
        try { service.byId(99); }
        catch (BookNotFoundException e) { System.out.println(e.getMessage()); }
    }
}
Output
BookResponse[id=7, title=Emma, author=Jane Austen, price=6.99]
BookResponse[id=8, title=Persuasion, author=Jane Austen, price=7.49]
BookResponse[id=7, title=Emma, author=Jane Austen, price=5.99]
Books left: 7
Book 99 was not found
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 setTitle(String title) { this.title = title; }
    public void setAuthor(String author) { this.author = author; }
    public void setPrice(double price) { this.price = price; }
}
Also uses BookRepository.java
public interface BookRepository extends JpaRepository<Book, Long> {

    List<Book> findByAuthorContainingIgnoreCase(String author);
}
Also uses CreateBook.java
public record CreateBook(
    @NotBlank String title,
    @NotBlank String author,
    @Positive double price
) {}
Also uses BookResponse.java
public record BookResponse(Long id, String title, String author, double price) {

    static BookResponse from(Book b) {
        return new BookResponse(b.getId(), b.getTitle(), b.getAuthor(), b.getPrice());
    }
}
Also uses NewPrice.java
public record NewPrice(@Positive double price) {}
Also uses BookNotFoundException.java
@ResponseStatus(HttpStatus.NOT_FOUND)
public class BookNotFoundException extends RuntimeException {
    public BookNotFoundException(long id) { super("Book " + id + " was not found"); }
}
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
Also uses BookService.java
@Service
@Transactional
public class BookService {

    private final BookRepository books;

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

    @Transactional(readOnly = true)
    public List<BookResponse> search(String author) {
        List<Book> found = author == null ? books.findAll()
                                          : books.findByAuthorContainingIgnoreCase(author);
        return found.stream().map(BookResponse::from).toList();
    }

    @Transactional(readOnly = true)
    public BookResponse byId(long id) { return BookResponse.from(find(id)); }

    public BookResponse create(CreateBook req) {
        Book saved = books.save(new Book(req.title(), req.author(), req.price()));
        return BookResponse.from(saved);
    }

    public BookResponse changePrice(long id, double price) {
        Book book = find(id);
        book.setPrice(price);
        return BookResponse.from(book);
    }

    public void delete(long id) { books.delete(find(id)); }

    private Book find(long id) {
        return books.findById(id).orElseThrow(() -> new BookNotFoundException(id));
    }
}

Summary

The repository searches by author, and the service holds the logic, inside transactions. Next, the controller.

Key takeaways
  • findByAuthorContainingIgnoreCase
  • @Transactional
  • BookNotFoundException
Next up: Project: The Controller — the HTTP layer