Spring Boot Repository and Service Layer: Save and Read Data Without Writing SQL
A one-line JpaRepository interface and a small @Service class save and read blog posts with no SQL. Follow one save and one read through every layer, then prove it with a test.
What you will learn
- Create a Spring Data JPA repository by extending JpaRepository
- Write a service class that gets the repository through constructor injection
- Follow one save and one read through the service, repository, Hibernate and H2
- Handle a missing row with Optional and test the service with @SpringBootTest
Before you start
- Java classes and interfaces
- A JPA @Entity class in Spring Boot
Our blog has a post table, but it's empty. In this step a Post finally gets saved, and we won't write one line of SQL for it. Two small pieces do the work: a repository and a service.
Where they sit in the blog
A blog like ours is built in layers, and one Post object travels through all of them:
- Web layer (
controller/): takes the request from the browser. - Service layer (
service/): where our own rules live. This step addsPostService. - Data layer (
repository/): does the database work. This step addsPostRepository, with Hibernate doing the SQL underneath. - Database: H2, in memory, keeps the rows.
Think of a library. The visitor is the controller. The librarian is the service. The storage room is the repository, and the shelves are the database. The visitor asks the librarian, the librarian sends someone to the storage room, and the book comes back the same way. Our own rules live with the librarian; the storage room only fetches and stores.
The hard way, and the one line that replaces it
Saving a post by hand means: open a connection, write the SQL in a string, put every field in one by one, read the rows back and copy each column into a Post, then close everything and handle the errors. Every save and every read repeats those steps.
With Spring Data JPA, all of that becomes one line: postRepository.save(post).
The entity we're saving
This is the Post entity from the previous step, unchanged:
package org.studyeasy.studyeasyblog.model;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import java.time.LocalDate;
@Entity
public class Post {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private String category;
private String excerpt;
private LocalDate publishedOn;
protected Post() {
}
public Post(String title, String category, String excerpt, LocalDate publishedOn) {
this.title = title;
this.category = category;
this.excerpt = excerpt;
this.publishedOn = publishedOn;
}
public Long getId() { return id; }
public String getTitle() { return title; }
public String getCategory() { return category; }
public String getExcerpt() { return excerpt; }
public LocalDate getPublishedOn() { return publishedOn; }
}
PostRepository: an empty interface that works
package org.studyeasy.studyeasyblog.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.studyeasy.studyeasyblog.model.Post;
public interface PostRepository extends JpaRepository<Post, Long> {
}
That's the whole file. Two types go in the angle brackets: Post is the entity, and Long is the type of its id. The body is empty: no methods, no SQL. Yet you get these for free:
| Method | SQL it runs |
|---|---|
save() | insert into post ... |
findAll() | select ... from post |
findById() | select ... from post where id = ? |
count() | select count(*) from post |
deleteById() | delete from post where id = ? |
Who writes the class behind the interface? Spring Data does, when the app starts.
PostService: the librarian
package org.studyeasy.studyeasyblog.service;
import org.springframework.stereotype.Service;
import org.studyeasy.studyeasyblog.model.Post;
import org.studyeasy.studyeasyblog.repository.PostRepository;
import java.util.List;
import java.util.Optional;
@Service
public class PostService {
private final PostRepository postRepository;
public PostService(PostRepository postRepository) {
this.postRepository = postRepository;
}
public List<Post> getAll() {
return postRepository.findAll();
}
public Optional<Post> getById(Long id) {
return postRepository.findById(id);
}
public Post save(Post post) {
return postRepository.save(post);
}
}
@Service: Spring creates this class and keeps it.private final PostRepository postRepository: a field that holds the repository.- The constructor fills that field. Spring passes the repository in.
getAll()returns aList<Post>by callingfindAll().getById(id)returns anOptional<Post>, because there might be no post with that id.save(post)returns the savedPost, now with its id.
Who creates the objects?
At startup, Spring Data sees the empty interface and builds an object that implements it, with save, findAll and findById inside. Then Spring creates PostService. Its constructor needs a repository, Spring has one ready, so it passes the repository object in and it lands in the postRepository field. This is constructor injection.
You never write new PostService(...) or new PostRepository(). Spring makes them and connects them.
One save, layer by layer
The caller calls postService.save with a new Post; its id is still null. The service calls postRepository.save with the same Post. The repository hands over to Hibernate, which builds the insert, and H2 stores the row and gives it an id. The Post travels back up through every layer: it is the same object you handed in, now with its id.
Reading goes the same way. getAll() calls findAll(), Hibernate builds a select, H2 answers with its rows, and Hibernate creates one Post per row (using the empty protected Post() constructor) and fills its fields from the columns. A List<Post> rides back to the caller.
Read one: Optional
getById(1) finds the row, and the post comes back inside an Optional: a small box with one Post in it. Ask for getById(99) and there's no such row, so the box comes back empty. Not an error, not a crash. The caller decides what to do with an empty box.
A test that plays the caller
No controller calls the service yet, so a test plays the caller:
package org.studyeasy.studyeasyblog.service;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.transaction.annotation.Transactional;
import org.studyeasy.studyeasyblog.model.Post;
import java.time.LocalDate;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest
@Transactional
class PostServiceTest {
@Autowired
private PostService postService;
@Test
void saveThenFindIt() {
int before = postService.getAll().size();
Post saved = postService.save(new Post("Hello, database", "Learning", "Our first saved post.", LocalDate.now()));
assertThat(saved.getId()).isNotNull();
assertThat(postService.getAll()).hasSize(before + 1);
assertThat(postService.getById(saved.getId())).isPresent();
}
}
It counts the posts with getAll(), saves a new one, checks that the database filled in the id, checks there's one more row, and finds the post again by id. Run it with mvnw test (or the green arrow in IntelliJ). Here's what the recorded run printed for this test:
Hibernate: select p1_0.id,p1_0.category,p1_0.excerpt,p1_0.published_on,p1_0.title from post p1_0
Hibernate: insert into post (category,excerpt,published_on,title,id) values (?,?,?,?,default)
Hibernate: select p1_0.id,p1_0.category,p1_0.excerpt,p1_0.published_on,p1_0.title from post p1_0
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 3.748 s -- in org.studyeasy.studyeasyblog.service.PostServiceTest
A select, the insert, and a second select: all written by Hibernate. The SQL is printed because of show-sql in the config below.
The setup behind it
The project uses Spring Boot 4.1.2 (Java 17 or newer) with spring-boot-starter-data-jpa, spring-boot-h2console and the h2 driver. application.yaml:
spring:
application:
name: StudyEasyblog
datasource:
url: jdbc:h2:mem:blogdb # a database in memory, named blogdb
jpa:
hibernate:
ddl-auto: create-drop # make the tables at startup, drop them at shutdown
show-sql: true # print every SQL statement
h2:
console:
enabled: true # http://localhost:8080/h2-console
Run the app with mvnw.cmd spring-boot:run on Windows or ./mvnw spring-boot:run on macOS and Linux.
Common mistakes
- Calling the repository straight from the controller. It works, but then your rules end up scattered. The service is the one place for them.
- Creating the service with
new.new PostService(...)skips Spring, so you'd have to build the repository yourself. Let Spring inject it. - Calling
.get()on the Optional without checking.getById(99)returns an empty box. Check it, or use something likeorElseThrow(), before you take the post out. - The wrong id type in
JpaRepository<Post, Long>. The second type must match the entity's@Idfield, which isLonghere.
Quick recap
| Piece | Job | In the blog |
|---|---|---|
| Repository | database work, written by Spring Data | PostRepository extends JpaRepository<Post, Long> |
| Service | our rules, in one place | PostService: getAll, getById, save |
| Constructor injection | Spring creates and connects the objects | public PostService(PostRepository postRepository) |
Optional<Post> | a box that may be empty | getById(99) gives an empty Optional |
| Test | plays the caller | Tests run: 1, Failures: 0 |
Try it yourself
Add a public long count() method to PostService that returns postRepository.count(), and print it at the end of the test. Which SQL does Hibernate print for it?
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (opens in a new tab)