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:
Step 2: Configure PostgreSQL Database Connection
In the application.properties
(or application.yml
) file, configure the PostgreSQL connection settings:
Replace your_database_name
, your_database_user
, and your_database_password
with your PostgreSQL credentials.
2. Create the User Entity (Model)
User.java
- This entity represents a user with an
id
,name
, andemail
. - 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 theid
is automatically generated by the database.
3. Create the Repository Interface
UserRepository.java
- This interface extends
JpaRepository
and provides CRUD operations for theUser
entity.
4. Create the Service Layer
UserService.java
- 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
@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 theid
.@PostMapping("/user/update")
: Updates the user in the database.@GetMapping("/user/delete/{id}")
: Deletes the user byid
.
6. Create Thymeleaf Templates
user-list.html
(To display the list of users)
user-form.html
(Form for creating or editing a user)
7. Run the Application
- Start the Spring Boot application.
- Access the application: Go to
http://localhost:8080/users
to view the list of users. - Use the "Create New User" link to add new users or edit existing ones.
Comments
Post a Comment