简介:In this article, we will create a simple Spring Boot application that uses Spring Data JPA for data access and Thymeleaf as the templating engine. We'll walk through setting up the project, creating a data model, configuring JPA and Thymeleaf, and finally building a simple CRUD (Create, Read, Update, Delete) application.
Spring Boot is a popular Java framework that allows developers to create standalone, production-grade applications with minimal configuration. It provides an easy way to create Spring-based projects by including a variety of features out of the box. Spring Data JPA is a library that simplifies the implementation of data access layers using the Java Persistence API (JPA). Thymeleaf is a modern server-side Java template engine that enables HTML5-friendly web development.
To create our simple Spring Boot application, we’ll use the Spring Initializr to generate a basic project structure. Here’s the step-by-step guide to setting up the project:
application.properties file and add the following configurations for your database connection:Make sure to replace
spring.datasource.url=jdbc//localhost:3306/mydb
spring.datasource.username=rootspring.datasource.password=rootspring.jpa.hibernate.ddl-auto=update
mydb with your desired database name.User in your project’s model package. Add the following code to define the data model:
package com.example.demo.model;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;@Entitypublic class User {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private Long id;private String name;private String email;// getters and setters omitted for brevity}
UserRepository in your project’s repository package.
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> {\n}
src/main/resources/templates in your project and add a Thymeleaf template called index.html.application.properties and add the following configuration to enable Thymeleaf:
thymeleaf.prefix=classpath:/templates/thymeleaf.suffix=.htmlthymeleaf.mode=HTML5thymeleaf.servlet.content-type=text/htmlthymeleaf.implicit-layouts=truethymeleafspring.thymeleaf.cache=false
UserController in your project’s controller package.