Sub topic 7
Putting business logic in a service
This chapter explains what the service layer is for and walks through BookService method by method. It also covers the mistakes that most often appear in this layer.
It assumes you know Java records and interfaces, and basic Spring dependency injection (a class receives the objects it needs from the Spring container). It also assumes you have the Book entity, BookRepository, BookRequest, BookResponse, and BookNotFoundException from the earlier chapters. Transactions get their own chapter, so this chapter mentions @Transactional only where it affects how the service reads.
Why a service layer exists
A request in this API passes through three layers:
- The controller handles HTTP: paths, status codes, and parsing JSON.
- The repository handles persistence: SQL, mapping, and queries.
- The service sits between them and holds the application's rules and workflow.
Without a service, those rules end up in the controller. A controller that checks "does this book exist?", then loads an entity, changes fields, and builds a response is hard to test without HTTP. It also cannot be reused by a scheduled job or a message listener.
With a service, each layer has one reason to change. The table shows who knows what.
| Layer | Knows about | Does not know about |
|---|---|---|
| Controller | HTTP, status codes, request parsing | SQL, entities' persistence state |
| Service | Business rules, DTO/entity conversion, exceptions | HTTP status codes, `ResponseEntity` |
| Repository | Queries, persistence | Business rules, DTOs |
The service class
Here is the full class from the plan, with its imports.
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class BookService {
private final BookRepository repository;
public BookService(BookRepository repository) {
this.repository = repository;
}
@Transactional(readOnly = true)
public Page<BookResponse> list(Pageable pageable) {
return repository.findAll(pageable).map(BookResponse::from);
}
@Transactional(readOnly = true)
public BookResponse get(Long id) {
return repository.findById(id)
.map(BookResponse::from)
.orElseThrow(() -> new BookNotFoundException(id));
}
@Transactional
public BookResponse create(BookRequest request) {
Book saved = repository.save(new Book(request.title(), request.author()));
return BookResponse.from(saved);
}
@Transactional
public BookResponse update(Long id, BookRequest request) {
Book book = repository.findById(id)
.orElseThrow(() -> new BookNotFoundException(id));
book.setTitle(request.title());
book.setAuthor(request.author());
return BookResponse.from(book);
}
@Transactional
public void delete(Long id) {
if (!repository.existsById(id)) {
throw new BookNotFoundException(id);
}
repository.deleteById(id);
}
}Reading the class piece by piece
`@Service` and constructor injection
@Service marks the class as a Spring bean (an object the container creates and manages) and tells readers it holds business logic. Functionally it behaves like @Component.
The class has one constructor, so Spring uses it automatically and no @Autowired is needed. The field is final, so the dependency cannot be replaced after construction. A test can also build the service with new BookService(fakeRepository), with no Spring container at all. Field injection (@Autowired on a private field) rules that out.
Entities stay inside the service
Every public method accepts and returns DTOs (data transfer objects, here BookRequest and BookResponse) or plain values such as Long. No method returns a Book. This is deliberate:
- The controller never touches a managed entity, so it cannot trigger lazy loading or accidental changes.
- Changes to the entity, such as a new column, do not change the JSON unless you change
BookResponse. - Jackson never serializes an entity, which avoids lazy-loading errors and infinite loops in bidirectional relationships.
The conversion happens in two places. BookResponse.from(book) maps an entity to a response. In create, new Book(request.title(), request.author()) maps a request to an entity.
Signaling errors without HTTP
get, update, and delete throw BookNotFoundException when the id does not exist. The service does not return null, an Optional, or a ResponseEntity.notFound(). It states the business fact "this book does not exist" and leaves the HTTP meaning to the exception handler. A later chapter maps this exception to a 404 response.
Because the exception extends RuntimeException, the method signatures stay clean. Spring's transaction support also rolls back on unchecked exceptions by default.
The update method and dirty checking
update never calls repository.save. Inside a transaction, findById returns a managed entity, which means JPA tracks its state. When you call the setters, JPA notices the fields changed (this is called dirty checking). At commit it issues an UPDATE statement.
This is correct, but it surprises many people. If you removed @Transactional from update, the entity would be detached as soon as findById returned. The setters would change an object nobody tracks, and nothing would reach the database. The code would still compile and the method would still return the new values.
Why `delete` checks first
deleteById behaves differently across Spring Data versions. Depending on the version, it either ignores a missing id or throws a Spring Data exception. Calling existsById first gives you one defined behavior: a missing id always produces BookNotFoundException. The cost is one extra query.
Read-only transactions
The read methods use @Transactional(readOnly = true). This is a hint, and the Hibernate JPA provider uses it to skip dirty checking. The next chapter explains transaction boundaries properly. For now, notice that the annotation sits on the service and not on the controller or repository, because the service method is the unit of work.
Where business rules go
The CRUD methods above contain almost no rules, which is normal for a first version. When a rule appears, it goes in the service. Here is an illustrative rule: no two books may have the same title and author. It needs a derived query in the repository and a new exception.
public interface BookRepository extends JpaRepository<Book, Long> {
boolean existsByTitleAndAuthor(String title, String author);
}public class DuplicateBookException extends RuntimeException {
public DuplicateBookException(String title, String author) {
super("Book '" + title + "' by " + author + " already exists");
}
}@Transactional
public BookResponse create(BookRequest request) {
if (repository.existsByTitleAndAuthor(request.title(), request.author())) {
throw new DuplicateBookException(request.title(), request.author());
}
Book saved = repository.save(new Book(request.title(), request.author()));
return BookResponse.from(saved);
}Check-then-insert has a race. Two concurrent requests can both pass the check and both insert. The service check gives a friendly error message in the common case. A unique constraint on the table is what actually enforces the rule. Use both.
Decide where each kind of check belongs:
| Check | Where |
|---|---|
| Title is not blank | Bean Validation on `BookRequest` |
| Book id exists | Service |
| Title and author pair is unique | Service for the message, database constraint for the guarantee |
| Response uses status 409 | Exception handler, not the service |
Testing the service in isolation
Because the service takes its repository through the constructor, you can test it with Mockito and no Spring context. These tests run in milliseconds.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
class BookServiceTest {
@Mock
private BookRepository repository;
@InjectMocks
private BookService service;
@Test
void getThrowsWhenBookIsMissing() {
when(repository.findById(1L)).thenReturn(Optional.empty());
assertThrows(BookNotFoundException.class, () -> service.get(1L));
}
@Test
void updateChangesFieldsOnTheLoadedBook() {
Book book = new Book("Old title", "Old author");
when(repository.findById(1L)).thenReturn(Optional.of(book));
BookResponse response = service.update(1L, new BookRequest("New title", "Ada"));
assertEquals("New title", response.title());
assertEquals("Ada", response.author());
}
@Test
void deleteDoesNotCallRepositoryDeleteForMissingBook() {
when(repository.existsById(5L)).thenReturn(false);
assertThrows(BookNotFoundException.class, () -> service.delete(5L));
verify(repository, never()).deleteById(5L);
}
}These tests cannot prove that dirty checking writes to the database. A mock repository has no persistence context. Only a test against a real database, such as @DataJpaTest, can show that.
Common mistakes
- Returning entities from the service. The controller then serializes them, which brings back lazy-loading and coupling problems.
- Putting HTTP concepts in the service. If a service method returns
ResponseEntityor throwsResponseStatusException, it can no longer be reused outside a web request. - Calling a
@Transactionalmethod from the same class. Spring applies transactions through a proxy, so a call from one method to another in the same class (this.update(...)) bypasses the proxy and its transaction settings. - Swallowing exceptions. Catching
RuntimeExceptioninside the service and returningnullhides failures and can prevent rollback. - A service that only forwards calls. If a method does nothing but call the repository, it is acceptable in a small CRUD API. It still gives you a place to add rules later without changing the controller.
Exercise
In BookService.update, there is no call to repository.save. Why does the change still reach the database, and what happens if you remove @Transactional from that method?
Show answer
findById runs inside a transaction and returns a managed entity. JPA tracks it, notices the changed title and author (dirty checking), and issues an UPDATE when the transaction commits. Without @Transactional, the entity is detached after findById returns, so the setters change an untracked object. The method still returns the new values, but the database row is not updated.
Exercise
A teammate wants BookService.get to return ResponseEntity.notFound().build() when the id is missing. Give two reasons to throw BookNotFoundException instead.
Show answer
First, the service stays independent of HTTP, so a scheduled job or a message listener can call it without handling web types. Second, the exception handler is the single place that decides how a missing book looks to clients, so every endpoint returns the same 404 body. Throwing also keeps the method's return type simple, because it returns a BookResponse and never a wrapper that callers must unpack.