Create and View Employee Using JPA, Springboot and Thymeleaf
Tags: springboot, thymeleaf, java, springdatajpa
Published: 2020-07-31 08:27:59

**Project Structure**

Here is the project structure.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/d4ox2gz0mwt5kge10ouc.png)

**Maven Dependencies pom.xml**
```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 https://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.3.2.RELEASE</version>
      <relativePath />
      <!-- lookup parent from repository -->
   </parent>
   <groupId>com.springboot.tutorial</groupId>
   <artifactId>springboot-helloworld-tutorial</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <name>CreateEmployee</name>
   <description>Demo project for Spring Boot</description>
   <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>
         <optional>true</optional>
      </dependency>
      <dependency>
         <groupId>mysql</groupId>
         <artifactId>mysql-connector-java</artifactId>
         <scope>runtime</scope>
      </dependency>
      <dependency>
         <groupId>org.projectlombok</groupId>
         <artifactId>lombok</artifactId>
         <scope>provided</scope>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
         <exclusions>
            <exclusion>
               <groupId>org.junit.vintage</groupId>
               <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
         </exclusions>
      </dependency>
   </dependencies>
   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>
</project>
```
**Domain Layer**

The domain layer is a collection of entity objects and related business logic that is designed to represent the business model.

Let's create a JPA **Employee** entity:

```java
package com.springboot.tutorial.entity;


import java.time.LocalDate;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import org.springframework.format.annotation.DateTimeFormat;
import lombok.Data;

@Entity
@Table(name="employee")
@Data
public class Employee {
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
	private int id;
	
	@Column(name = "name")
	private String name;
	
	@Column(name = "age")
	private int age;
	
	@Column(name = "gender")
	private String gender;
	
	@Column(name = "joiningDate")
	@DateTimeFormat(pattern = "yyyy-MM-dd")
	private LocalDate joiningDate;
	
	@Column(name = "retiringDate")
	@DateTimeFormat(pattern = "yyyy-MM-dd")
	private LocalDate retiringDate;
	
	@Column(name="dept")
	private String dept;

}

```

**Controller Layer**

This layer is responsible for processing the user’s input and returning the correct response back to the user.

Let’s create an **EmployeeController** class to send requests and bind data to the user’s view.

```java
package com.springboot.tutorial.controller;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.springboot.tutorial.entity.Employee;
import com.springboot.tutorial.service.EmployeeService;

@Controller
public class EmployeeController {

	@Autowired
	private EmployeeService service;

	@RequestMapping("/")
	public String viewHomePage(Model model) {
		List<Employee> employeeList = service.listAll();
		model.addAttribute("listAll", employeeList);
		return "index";
	}

	@RequestMapping("/new")
	public String showNewEmployeePage(Model model) {
		Employee employee = new Employee();
		model.addAttribute("employee", employee);
		return "new_employee";
	}

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public String saveEmployee(@ModelAttribute("employee") Employee employee, Model model, BindingResult result) {
		service.save(employee);
		List<Employee> employeeList = service.listAll();
		model.addAttribute("listAll", employeeList);
		model.addAttribute("employeeAttr", employee);
		return "index";
	}
}
```

**Service Layer**

This layer is the middleware between Controller and Repository. 

The service gathers data from controller, performs validation and business logic, and calling repositories for data manipulation.

Let’s create **EmployeeService** interface to send the user’s requests from Controller to Repository.

```java
package com.springboot.tutorial.service;

import java.util.List;
import com.springboot.tutorial.entity.Employee;
public interface EmployeeService {

	List < Employee > listAll();

	void save(Employee employee);

}
```

And create **EmployeeServiceImpl** class that implements **EmployeeService** interface and connect to Repository by using **@Autowired** keyword.

```java
package com.springboot.tutorial.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.springboot.tutorial.entity.Employee;
import com.springboot.tutorial.repository.EmployeeRepository;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeRepository repo;

    @Override
    public List < Employee > listAll() {
        return repo.findAll();
    }

    @Override
    public void save(Employee emp) {
        repo.save(emp);
    }
}
```

**Repository Layer**

**Spring Data JPA** allows implementing JPA-based repositories 

We don't need to write any DAO code but Spring Data JPA will generate an implementation automatically at runtime.

Let's create an **EmployeeRepository** class with the following code:

```java
package com.springboot.tutorial.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.springboot.tutorial.entity.Employee;
@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {

}

```

**View Layer**

We need to create the HTML pages for displaying the Employee’s registration form and showing the registered Employee’s list under the **src/main/resources/templates** folder.

We will use Thymeleaf as the underlying template engine for parsing the template files.

Let’s create an **index.html**  as a welcome page and to show the registered Employee’s list.

```html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
   xmlns:th="http://www.thymeleaf.org">
   <head>
      <meta charset="utf-8" />
      <title>Employee Management</title>
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
      <link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css">
      <script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
      <script type="text/javascript">
         $(document).ready(function() {
         	$('#data-table').DataTable();
         });
      </script>
   </head>
   <body>
      <div class="content">
         <div class="animated fadeIn">
            <div class="row">
               <div class="col-md-12">
                  <div class="card">
                     <div class="card-header">
                        <strong class="card-title">
                           <h1 style="text-align: center; color: #b30000; font-weight: bold;">EMPLOYEE MANAGEMENT</h1>
                        </strong>
                        <div style="text-align: center; font-weight: bold">
                           <a href="new">Create New Employee</a> <br /> 
                        </div>
                     </div>
                     <div class="card-body">
                        <table id="data-table" class="table table-striped table-bordered">
                           <thead>
                              <tr>
                                 <th>Employee ID</th>
                                 <th>Name</th>
                                 <th>Age</th>
                                 <th>Department</th>
                                 <th>Gender</th>
                                 <th>Joining Date</th>
                                 <th>Retiring Date</th>
                              </tr>
                           </thead>
                           <tbody>
                              <tr th:each="employee:${listAll}">
                                 <td th:text="${employee.id}">Product ID</td>
                                 <td th:text="${employee.name}">Name</td>
                                 <td th:text="${employee.age}">Age</td>
                                 <td th:text="${employee.dept}">Department</td>
                                 <td th:text="${employee.gender}">Gender</td>
                                 <td th:text="${employee.joiningDate}">Joining Date</td>
                                 <td th:text="${employee.retiringDate}">Retiring Date</td>
                              </tr>
                           </tbody>
                        </table>
                     </div>
                  </div>
               </div>
            </div>
         </div>
      </div>
   </body>
</html>
```

And create a **new_employee.html**  page as a registration form page.

```html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
   xmlns:th="http://www.thymeleaf.org">
   <head>
      <meta charset="utf-8" />
      <title>Create New Employee</title>
      <link rel="stylesheet"
         href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
      <link rel="stylesheet" href="/resources/demos/style.css">
      <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
      <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
      <script>
         $(function() {
         	$("#join_datepicker").datepicker({
         		dateFormat : "yy-mm-dd"
         	});
         	$("#retire_datepicker").datepicker({
         		dateFormat : "yy-mm-dd"
         	});
         });
      </script>
   </head>
   <body>
      <div align="center">
         <h1>Create New Emloyee</h1>
         <br />
         <form action="#" th:action="@{/save}" th:object="${employee}"
            method="post">
            <table border="0" cellpadding="10">
               <tr>
                  <td>Employee Name:</td>
                  <td><input type="text" th:field="*{name}" /></td>
               </tr>
               <tr>
                  <td>Age:</td>
                  <td><input type="text" th:field="*{age}" /></td>
               </tr>
               <tr>
                  <td>Department:</td>
                  <td>
                     <select th:field="*{dept}">
                        <option th:value="IT" th:text="IT"></option>
                        <option th:value="HR" th:text="HR"></option>
                        <option th:value="Sales" th:text="Sales"></option>
                     </select>
                  </td>
               </tr>
               <tr>
                  <td>Gender:</td>
                  <td><input type="radio" th:field="*{gender}" th:value="Male"
                     th:text="Male" /> <input type="radio" th:field="*{gender}"
                     th:value="Female" th:text="Female" /></td>
               </tr>
               <tr>
                  <td>Joining Date:</td>
                  <td><input type="date" id="join_datepicker"
                     th:field="*{joiningDate}"></td>
               </tr>
               <tr>
                  <td>Retiring Date:</td>
                  <td><input type="date" id="retire_datepicker"
                     th:field="*{retiringDate}"></td>
               </tr>
               <tr>
                  <td colspan="2"><button type="submit">Save</button></td>
               </tr>
            </table>
         </form>
      </div>
   </body>
</html>
```

**Running the Application**

Let's access web application using http://localhost:8080. Initially, you don't have any employee in the list. 

Let's add a new employee first.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/cgodxnj7g6ezt0hpa0kf.png)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/mm5hvdoifnt5dx93h1py.png)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/vyya33vg8hpze6k5a8m2.png)

You can download the source code at 
[github](https://github.com/ThiriYadanar/CreateEmployee/tree/EmployeeRegistration)