User Management System using Spring Boot and Thymeleaf

 To create a Spring Boot CRUD application using JPA, PostgreSQL, and Thymeleaf, follow the steps below. This example will demonstrate a simple User Management System where you can create, read, update, and delete users.

1. Set up Spring Boot Application with PostgreSQL

Step 1: Add Dependencies

In your pom.xml (for Maven), add the required dependencies for Spring Boot, JPA, PostgreSQL, and Thymeleaf:

<dependencies> <!-- Spring Boot Starter Web (includes REST, Spring MVC, etc.) --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Spring Boot Starter Data JPA (for working with databases) --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <!-- PostgreSQL Database Driver --> <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> </dependency> <!-- Thymeleaf Template Engine --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <!-- Spring Boot Starter for Testing --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>

Step 2: Configure PostgreSQL Database Connection

In the application.properties (or application.yml) file, configure the PostgreSQL connection settings:

# PostgreSQL database configuration spring.datasource.url=jdbc:postgresql://localhost:5432/your_database_name spring.datasource.username=your_database_user spring.datasource.password=your_database_password spring.datasource.driver-class-name=org.postgresql.Driver # JPA Configuration spring.jpa.hibernate.ddl-auto=update # Automatically update DB schema spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect # Enable SQL logging spring.jpa.show-sql=true spring.jpa.properties.hibernate.format_sql=true

Replace your_database_name, your_database_user, and your_database_password with your PostgreSQL credentials.


2. Create the User Entity (Model)

User.java

package com.example.demo.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private String email; // Getters and Setters public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
  • This entity represents a user with an id, name, and email.
  • The @Entity annotation tells JPA that this is a JPA entity, and @Id marks the primary key field.
  • The @GeneratedValue(strategy = GenerationType.IDENTITY) ensures that the id is automatically generated by the database.

3. Create the Repository Interface

UserRepository.java

package com.example.demo.repository; import com.example.demo.model.User; import org.springframework.data.jpa.repository.JpaRepository; public interface UserRepository extends JpaRepository<User, Long> { }
  • This interface extends JpaRepository and provides CRUD operations for the User entity.

4. Create the Service Layer

UserService.java

package com.example.demo.service; import com.example.demo.model.User; import com.example.demo.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service public class UserService { @Autowired private UserRepository userRepository; public List<User> getAllUsers() { return userRepository.findAll(); } public Optional<User> getUserById(Long id) { return userRepository.findById(id); } public User createUser(User user) { return userRepository.save(user); } public User updateUser(User user) { return userRepository.save(user); } public void deleteUser(Long id) { userRepository.deleteById(id); } }
  • The UserService class acts as a service layer to handle the logic for CRUD operations.
  • It uses the UserRepository to interact with the database.

5. Create the Controller

UserController.java

package com.example.demo.controller; import com.example.demo.model.User; import com.example.demo.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; @Controller public class UserController { @Autowired private UserService userService; // Display the list of users @GetMapping("/users") public String getAllUsers(Model model) { model.addAttribute("users", userService.getAllUsers()); return "user-list"; } // Show form to create a new user @GetMapping("/user/new") public String showCreateUserForm(Model model) { model.addAttribute("user", new User()); return "user-form"; } // Create a new user @PostMapping("/user/save") public String saveUser(@ModelAttribute User user) { userService.createUser(user); return "redirect:/users"; } // Show form to edit an existing user @GetMapping("/user/edit/{id}") public String showEditUserForm(@PathVariable("id") Long id, Model model) { User user = userService.getUserById(id).orElseThrow(() -> new IllegalArgumentException("Invalid user ID: " + id)); model.addAttribute("user", user); return "user-form"; } // Update an existing user @PostMapping("/user/update") public String updateUser(@ModelAttribute User user) { userService.updateUser(user); return "redirect:/users"; } // Delete a user @GetMapping("/user/delete/{id}") public String deleteUser(@PathVariable("id") Long id) { userService.deleteUser(id); return "redirect:/users"; } }
  • @GetMapping("/users"): Fetches all users from the database and displays them.
  • @GetMapping("/user/new"): Displays a form to create a new user.
  • @PostMapping("/user/save"): Saves the newly created user to the database.
  • @GetMapping("/user/edit/{id}"): Displays the form to edit an existing user based on the id.
  • @PostMapping("/user/update"): Updates the user in the database.
  • @GetMapping("/user/delete/{id}"): Deletes the user by id.

6. Create Thymeleaf Templates

user-list.html (To display the list of users)

<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>User List</title> </head> <body> <h1>User List</h1> <a href="/user/new">Create New User</a> <table> <thead> <tr> <th>ID</th> <th>Name</th> <th>Email</th> <th>Actions</th> </tr> </thead> <tbody> <tr th:each="user : ${users}"> <td th:text="${user.id}"></td> <td th:text="${user.name}"></td> <td th:text="${user.email}"></td> <td> <a th:href="@{/user/edit/{id}(id=${user.id})}">Edit</a> <a th:href="@{/user/delete/{id}(id=${user.id})}">Delete</a> </td> </tr> </tbody> </table> </body> </html>

user-form.html (Form for creating or editing a user)

<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>User Form</title> </head> <body> <h1 th:text="${user.id == null ? 'Create' : 'Edit'} + ' User'"></h1> <form th:action="@{${user.id == null ? '/user/save' : '/user/update'}}" th:object="${user}" method="post"> <label for="name">Name:</label> <input type="text" th:field="*{name}" id="name"/> <br/> <label for="email">Email:</label> <input type="text" th:field="*{email}" id="email"/> <br/> <button type="submit">Submit</button> </form> </body> </html>

7. Run the Application

  1. Start the Spring Boot application.
  2. Access the application: Go to http://localhost:8080/users to view the list of users.
  3. Use the "Create New User" link to add new users or edit existing ones.

Comments