Sub topic 7
Putting business logic in a service
This chapter assumes you have a Book entity, a BookRepository, and the BookRequest and BookResponse records from the earlier chapters. You should also know what constructor injection is.
Why a service layer
The controller handles HTTP: paths, status codes, and request bodies. The repository handles persistence. Neither is a good place for the rules of your application, such as "an update to a missing book is an error". A service class sits between them and holds those rules.
This gives you three benefits:
- The controller stays thin and only translates between HTTP and Java calls.
- Rules live in one place, so a second caller (a scheduled job, a message listener) reuses them.
- The service can be tested without starting a web server.
The service
@Service registers the class as a Spring bean. The repository arrives through the constructor. With a single constructor, Spring needs no @Autowired.
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);
}
}What each method does
- Conversion. Every public method accepts and returns DTOs. Entities never leave the service, so the JSON contract cannot change by accident when you edit the entity.
- Missing resources.
get,update, anddeletethrowBookNotFoundExceptionwhen the id does not exist. The service reports the problem in domain terms and knows nothing about HTTP. - Update without
save.updateloads the entity, changes it with setters, and never callsrepository.save. Inside a transaction, the loaded entity is managed. Hibernate compares it to its original state at commit (dirty checking) and issues anUPDATE. The next chapter covers transaction boundaries. - Existence check on delete.
deleteByIdbehaves differently across Spring Data versions when the id is missing. The explicitexistsByIdcheck makes the 404 behavior certain.
The exception
public class BookNotFoundException extends RuntimeException {
public BookNotFoundException(Long id) {
super("Book " + id + " not found");
}
}The exception is unchecked, so callers are not forced to catch it. A later chapter maps it to a 404 response in one central place.
Common mistakes
- Returning entities from the service. Entities then leak into the controller and into JSON. Lazy associations can fail when serialized after the transaction has ended.
- Putting
@Transactionalon private methods. Spring applies it through a proxy, so only calls from outside the bean pass through it. - Field injection with
@Autowired. It hides dependencies and makes plain unit tests harder. A constructor lets you writenew BookService(mockRepository). - Calling
saveafter changing a managed entity. This is harmless, but it suggests the update only works because ofsave.
Exercise
In update, the code never calls repository.save(book), yet the new title is stored. Why, and what would break if you removed @Transactional from update?
Show answer
The Book returned by findById is a managed entity inside the transaction. When the transaction commits, Hibernate detects the changed fields (dirty checking) and writes an UPDATE. Without @Transactional, findById runs in its own short transaction and returns a detached entity. The setter changes would not be persisted, so the response would show the new values while the database kept the old ones.