Employee Management System Data Layer

Learn via video courses
Topics Covered

Overview

Repository is a way to interact with the database. Spring boot offers out of box repository to interact with Database with a minimum amount of the code.

Prerequisite

  • Reader should checkout and go through the following code.

Add Required Dependencies

We are going to build a data layer using MySQL, therefore dependencies we need are starter-data-jpa dependency and MySQL driver.

Configure Datasource

We need to configure the required properties in order to configure MySQL data source in application.properties

Create Entity

Let's create an Employee entity in the com.scaler.ems.entities package and add the following content to it:

Create a Repository

Create an EmployeeRepository and extend it from JpaRepository

Create Tables

There are several ways to create the table in the database but for this article, we will use hibernate way to create a table during application startup.

The above property creates a table in the target schema if it does not exist.

Unit Test Repositories

Spring Boot provides the @DataJpaTest annotation to test Spring Data JPA repositories or any other JPA-related components. @DataJpaTest connect to h2 database. Therefore we need to add h2 dependency in our pom with scope test.

Let's write a test case for repository EmployeeRepositoryTest

The source code for this article is available at the GitHub location under tag version_4.0.0_DL_FINAL

Conclusion

In this article, we have covered the following:

  • Build data layer for spring boot.
  • Test data layer using @DataJpaTest annotation.