Seed Data and Posts on the Homepage: CommandLineRunner, the Model and th:each
SeedData, a CommandLineRunner, saves three posts when the POST table is empty. HomeController puts postService.getAll() into the Model, and one postCard inside th:each becomes three cards. Three inserts at startup, one select per visit.
What you will learn
- Save sample rows once at startup with a CommandLineRunner
- Pass a List of Post from the controller to the page through the Model
- Repeat one Thymeleaf card for every post with th:each
- Follow a request down the layers and the objects back up
Before you start
- Entities and H2 in Spring Boot
- Repositories and a Service Layer
The homepage cards are still typed into home.html. Today they come from the database. A few sample rows go in when the app starts, and the page just reads them back. Same page, same design; only the place the text comes from changes.
Stock the shelves before the shop opens
package org.studyeasy.studyeasyblog.config;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.studyeasy.studyeasyblog.model.Post;
import org.studyeasy.studyeasyblog.service.PostService;
import java.time.LocalDate;
@Component
public class SeedData implements CommandLineRunner {
private final PostService postService;
public SeedData(PostService postService) {
this.postService = postService;
}
@Override
public void run(String... args) {
if (postService.getAll().isEmpty()) {
postService.save(new Post("Hello from the database", "Community",
"This card comes from a row in the POST table, not from the HTML.",
LocalDate.of(2024, 6, 12)));
postService.save(new Post("Spring Boot in plain words", "Learning",
"A small app, a few classes, and Spring wires them together for us.",
LocalDate.of(2024, 6, 8)));
postService.save(new Post("Why we start with H2", "Inspiration",
"A database in memory: nothing to install, fresh on every start.",
LocalDate.of(2024, 6, 2)));
}
}
}
@Component makes Spring create the class at startup. Because it implements CommandLineRunner, Spring calls its run method once, right after startup. The PostService comes in through the constructor. Inside run, the first question is "are there no posts yet?" The service asks the repository, the repository runs a select on POST, nothing comes back, so it saves three posts. Each save goes through the service and the repository, and Hibernate turns it into an insert.
The controller passes the posts on
@Controller
public class HomeController {
private final PostService postService;
public HomeController(PostService postService) {
this.postService = postService;
}
@GetMapping("/")
public String home(Model model) {
model.addAttribute("posts", postService.getAll());
return "home";
}
// post, about and author mappings as before
}
Spring calls home with an empty Model, a box for the page. One line fills it: addAttribute("posts", ...) with the list from the service. Then return "home", and Thymeleaf renders home.html with that Model.
One card, repeated
<th:block th:each="post : ${posts}">
<div th:replace="~{fragments/layout :: postCard(${post.title}, ${post.category},
${#temporals.format(post.publishedOn, 'MMMM d, yyyy')}, ${post.excerpt},
@{/posts/{id}(id=${post.id})})}"></div>
</th:block>
Three typed cards became one. th:each repeats it for every post in the list. ${post.title} calls getTitle(); category and excerpt work the same way. The date goes through #temporals.format so it reads like a normal date, and the id builds the link, /posts/1. The card itself is the postCard fragment from the design step.
Down the layers and back up
A visitor opens /. Spring calls HomeController.home, which asks PostService, which asks the repository, which runs one select on POST and reads three rows. On the way back, Hibernate makes an empty Post for each row and fills its fields: three rows, three objects. The repository returns them as a List<Post>, the service passes it on, the controller puts it in the Model, and Thymeleaf makes one card per post. Objects, not rows, travel up through the layers.
Three rows, three cards
Run the app and the homepage shows "Hello from the database", "Spring Boot in plain words" and "Why we start with H2". In the console, SeedData's check runs one select, three inserts follow, and each visit to the page adds one more select. In the H2 console, SELECT * FROM POST shows the same three rows.
Common mistakes
- Dropping the
isEmpty()check. With a database that keeps its data, every restart would add three more copies. - Naming the Model attribute
postbut looping over${posts}. The names must match. - Printing
publishedOnraw. Without#temporals.formatyou get2024-06-12instead of a readable date.
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
Related course on Udemy
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 (paid course, opens in a new tab)Related posts
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.
Entities and H2 in Spring Boot: a Post Class Becomes a Table
The blog's cards are typed into HTML. A Post class with @Entity and @Id becomes the POST table in an in-memory H2 database: three pom lines, a few YAML settings, and Hibernate writes the create table SQL at startup.
Pagination and Sorting on a Spring Boot Homepage: PageRequest In, Page Out
Eight posts, three to a page, newest first. HomeController turns ?page=1&sort=oldest into a PageRequest, PostService passes it to findAll(Pageable), H2 runs one select with an offset and one count, and the Page that comes back knows it is page 2 of 3.
Connect Spring Boot to PostgreSQL: Driver, application.yml and the Hikari Pool
Connect the Relay support desk to PostgreSQL 18: one compose service, one driver line in the pom, a datasource in application.yml with a strict prod profile, and a small runner that asks the server who it is through the Hikari pool.
