Skip to main content

Spring Boot-JPA-Thymeleaf-CRUD project with source code

In this article, we will show you how to develop a Spring Boot CRUD web application, using Thymeleaf view, embedded Tomcat and JPA.
User Interface

Following technologies stack being used:

  • Spring Boot 2.1.4.RELEASE
  • Spring 5.1.6.RELEASE 
  • Maven 3
  • JDK 1.8
  • Eclipse Oxygen
  • Bootstrap
  • Thymeleaf
  • H2DB -in memory database

Project Structure

Pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>2.1.4.RELEASE</version>
  <relativePath /> <!-- lookup parent from repository -->
 </parent>
 <artifactId>springboot-jpa-thymeleaf-crud</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <name>springboot-jpa-thymeleaf-crud</name>
 <properties>
  <java.version>1.8</java.version>
 </properties>
 <dependencies>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-jpa</artifactId>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-thymeleaf</artifactId>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-devtools</artifactId>
   <scope>runtime</scope>
  </dependency>
  <dependency>
   <groupId>com.h2database</groupId>
   <artifactId>h2</artifactId>
   <scope>runtime</scope>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
  </dependency>
  <!-- https://mvnrepository.com/artifact/javax.validation/validation-api -->
  <dependency>
   <groupId>javax.validation</groupId>
   <artifactId>validation-api</artifactId>
     </dependency>
 </dependencies>
 <build>
  <plugins>
   <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
   </plugin>
  </plugins>
 </build>
<description>springboot-jpa-thymeleaf-crud</description>
  <groupId>com.knowledgefactory</groupId>
</project>
WebController
package com.knowledgefactory.controller;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import com.knowledgefactory.entity.User;
import com.knowledgefactory.exception.RecordNotFoundException;
import com.knowledgefactory.service.UserService;
@Controller
public class WebController {
 @Autowired
 UserService service;
 @GetMapping({ "/" })
 public String getAllUsers(Model model) {
  List<User> list = service.getAllusers();
  System.out.println(list);
  model.addAttribute("users", list);
  return "list-users";
 }
 @GetMapping(path = { "/edit", "/edit/{id}" })
 public String editUserById(Model model, @PathVariable("id") Optional<Long> id) throws RecordNotFoundException {
  if (id.isPresent()) {
   User entity = service.getUserById(id.get());
   model.addAttribute("user", entity);
  } else {
   model.addAttribute("user", new User());
  }
  return "add-edit-user";
 }
 @GetMapping(path = "/delete/{id}")
 public String deleteUserById(Model model, @PathVariable("id") Long id) throws RecordNotFoundException {
  service.deleteUserById(id);
  return "redirect:/";
 }
 @PostMapping(path = "/createUser")
 public String createOrUpdateUser(User user) {
  service.createOrUpdateUser(user);
  return "redirect:/";
 }
}
User(Entity Class)
package com.knowledgefactory.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "user")
public class User {
 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 private Long id;
 @Column(name = "first_name")
 private String firstName;
 @Column(name = "last_name")
 private String lastName;
 @Column(name = "email", nullable = false, length = 200)
 private String email;
 public User() {
  super();
 }
 public Long getId() {
  return id;
 }
 public void setId(Long id) {
  this.id = id;
 }
 public String getFirstName() {
  return firstName;
 }
 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }
 public String getLastName() {
  return lastName;
 }
 public void setLastName(String lastName) {
  this.lastName = lastName;
 }
 public String getEmail() {
  return email;
 }
 public void setEmail(String email) {
  this.email = email;
 }
 public User(String firstName, String lastName, String email) {
  super();
  this.firstName = firstName;
  this.lastName = lastName;
  this.email = email;
 }
 @Override
 public String toString() {
  return "User [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]";
 }
}
UserRepository
package com.knowledgefactory.repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.knowledgefactory.entity.User;
@Repository
public interface UserRepository extends CrudRepository<User, Long> {
}
UserService
package com.knowledgefactory.service;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.knowledgefactory.entity.User;
import com.knowledgefactory.exception.RecordNotFoundException;
import com.knowledgefactory.repository.UserRepository;
@Service
public class UserService {
 @Autowired
 UserRepository repository;
 public List<User> getAllusers() {
  List<User> result = (List<User>) repository.findAll();
  if (result.size() > 0) {
   return result;
  } else {
   return new ArrayList<User>();
  }
 }
 public User getUserById(Long id) throws RecordNotFoundException {
  Optional<User> user = repository.findById(id);
  if (user.isPresent()) {
   return user.get();
  } else {
   throw new RecordNotFoundException("No user record exist for given id");
  }
 }
 public User createOrUpdateUser(User entity) {
  if (entity.getId() == null) {
   entity = repository.save(entity);
   return entity;
  } else {
   Optional<User> user = repository.findById(entity.getId());
   if (user.isPresent()) {
    User newEntity = user.get();
    newEntity.setEmail(entity.getEmail());
    newEntity.setFirstName(entity.getFirstName());
    newEntity.setLastName(entity.getLastName());
    newEntity = repository.save(newEntity);
    return newEntity;
   } else {
    entity = repository.save(entity);
    return entity;
   }
  }
 }
 public void deleteUserById(Long id) throws RecordNotFoundException {
  Optional<User> user = repository.findById(id);
  if (user.isPresent()) {
   repository.deleteById(id);
  } else {
   throw new RecordNotFoundException("No user record exist for given id");
  }
 }
}
Spring Boot(Main Class)
package com.knowledgefactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.knowledgefactory.entity.User;
import com.knowledgefactory.repository.UserRepository;
@SpringBootApplication
public class KnowledgefactorydemoApplication implements CommandLineRunner {
 @Autowired
 private UserRepository repository;
 public static void main(String[] args) {
  SpringApplication.run(KnowledgefactorydemoApplication.class, args);
 }
 @Override
 public void run(String... args) throws Exception {
  repository.save(new User("sibin", "knf", "sibinraziya@gmail.com"));
 }
}
add-edit-user.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Add User</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
 href="https://use.fontawesome.com/releases/v5.4.1/css/all.css">
<link rel="stylesheet" type="text/css" media="all"
 href="../../bootstrap.min.css" th:href="@{/bootstrap.min.css}" />
</head>
<body>
 <div class="container my-5">
  <h3>Add User</h3>
  <div class="card">
   <div class="card-body">
    <div class="col-md-10">
     <form action="#" th:action="@{/createUser}" th:object="${user}"
      method="post">
      <div class="row">
       <div class="form-group col-md-8">
        <label for="name" class="col-form-label">First Name</label> <input
         type="text" th:field="*{firstName}" class="form-control"
         id="firstName" placeholder="First Name" />
       </div>
       <div class="form-group col-md-8">
        <label for="name" class="col-form-label">Last Name</label> <input
         type="text" th:field="*{lastName}" class="form-control"
         id="lastName" placeholder="Last Name" />
       </div>
       <div class="form-group col-md-8">
        <label for="email" class="col-form-label">Email</label> <input
         type="text" th:field="*{email}" class="form-control" id="email"
         placeholder="Email Id" />
       </div>
       <div class="col-md-6">
        <input type="submit" class="btn btn-success" value=" Submit ">
       </div>
       <input type="hidden" id="id" th:field="*{id}">
      </div>
     </form>
    </div>
   </div>
  </div>
 </div>
</body>
</html>
list-users.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>All Users</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="all"
 href="../../bootstrap.min.css" th:href="@{/bootstrap.min.css}" />
<link rel="stylesheet"
 href="https://use.fontawesome.com/releases/v5.4.1/css/all.css">
</head>
<body>
 <div class="container my-2">
  <div class="card">
   <div class="card-body">
    <div th:switch="${users}" class="container my-5">
     <p class="my-5">
      <a href="/edit" class="btn btn-success"> <i
       class="fas fa-user-plus ml-2"> Add User </i></a>
     </p>
     <div class="col-md-10">
      <h2 th:case="null">No record found !!</h2>
      <div th:case="*">
       <table class="table table-striped table-responsive-md">
        <thead>
         <tr>
          <th>First Name</th>
          <th>Last Name</th>
          <th>Email</th>
          <th>Edit</th>
          <th>Delete</th>
         </tr>
        </thead>
        <tbody>
         <tr th:each="user : ${users}">
          <td th:text="${user.firstName}"></td>
          <td th:text="${user.lastName}"></td>
          <td th:text="${user.email}"></td>
          <td><a th:href="@{/edit/{id}(id=${user.id})}"
           class="btn btn-warning"> <i class="fas fa-user-edit ml-2"></i>
          </a></td>
          <td><a th:href="@{/delete/{id}(id=${user.id})}"
           class="btn btn-danger"> <i class="fas fa-user-times ml-2"></i>
          </a></td>
         </tr>
        </tbody>
       </table>
      </div>
     </div>
    </div>
   </div>
  </div>
 </div>
</body>
</html>
Run
$ mvn spring-boot:run

Comments

Popular posts from this blog

Spring boot video streaming example-HTML5

This article shows you how to stream MP4 video in Spring Boot web application 
User Interface

Project Structure

Home Controller
@Controller
public class HomeController {
 @Autowired
 private MyResourceHttpRequestHandler handler;
 private final static File MP4_FILE = new File("D:\\videofiles\\video1.mp4");
 // supports byte-range requests
 @GetMapping("/index")
 public String home() {
  return "index";
 }
 // supports byte-range requests
 @GetMapping("/byterange")
 public void byterange( HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  request.setAttribute(MyResourceHttpRequestHandler.ATTR_FILE, MP4_FILE);
  handler.handleRequest(request, response);
 }}
Spring Boot 
@SpringBootApplication
@ComponentScan({ "com" })
public class KnowledgefactorydemoApplication {
 public static void main(String[] args) {
  SpringApplication.run(KnowledgefactorydemoApplication.class, args);
 }}
MyResource HttpRequestHandler
@Componen…

DataTable-Pagination example with Spring boot,jQuery and ajax free download

This article shows you DataTable-Pagination example with Spring boot, jQuery and ajax. 

Following technologies stack being used:
Spring Boot 2.1.1.RELEASESpring 5.1.3.RELEASE Maven 3DatatablejQueryFree Markerjavascriptajax Project Structure
View(index.ftl) <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Knf|Pagination-Datatables</title> <!-- Tell the browser to be responsive to screen width --> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="../../css/jquery.dataTables.min.css"> <body>  <section class="content">   <div class="container-fluid">    <table id="example" class="display" style="width: 100%">     <thead>      <tr>       <th>First name</th>       <th>La…

9 Best Job Posting Sites for Employee 2020-2022

One of the most common ways today’s job seekers uncover employment opportunities are by using online sources. There are hundreds of job boards, both generic and niche, as well as aggregators, social media channels, networking groups, and staffing company websites to choose from. The good news is they provide plenty of listings. The bad news is you can be easily overwhelmed by so many options. Here, knowledge factory offers 9 of what is generally considered the best job search websites around. There are many others, of course, but this list of best job search websites should give you a good starting point for your next job hunt: 1. LinkedIn
This top networking site allows you to find jobs through your extended network. User profiles serve as resumes. You can easily share career-related content and solicit or supply recommendations. Additionally, you can join groups, participate in conversations, and follow companies you find interesting and relevant to your job search. Premium pai…