Skip to content
Tutorials Center
My learning

Topics

Lesson 115 of 119 ยท Projects

Project: Employee Management with Spring Data JPA

Build an employee management API with Spring Boot and Spring Data JPA: related entities, query methods, specifications, paging, DTOs, validation and tests.

The task API in the previous projects had a single table. Real business applications rarely do. In this project you build the back end of a small HR tool: departments and the employees who work in them. Two related entities are enough to bring in the problems you meet every day with Spring Data JPA: a @ManyToOne relationship that must be loaded efficiently, searches with optional filters, paging and sorting that come straight from query parameters, rules that need the database ("this email is already taken"), reports built with aggregate queries, and concurrent edits.

The application is written in Spring Boot 4 with Spring Data JPA, Bean Validation and Spring MVC. Spring can't run in this page's editor, so the project works on two tracks, the same way as Project: Task API with Spring Boot:

  • The real application is shown file by file, read-only, in the order you would write it.
  • Four runnable stages rebuild each layer in plain Java on H2, Jackson and com.sun.net.httpserver, so you can see exactly what Spring does for you: the SQL behind the repositories, the validation that @Valid triggers, what @Transactional binds to the thread, how a Pageable is read from the URL, and how exceptions become problem details.

You should know Spring Data JPA, Entity Relationships and Validation and Error Handling. Each stage is a complete program, because every run starts fresh.

What you will build

The API manages departments and employees. Department ids and employee ids are numbers assigned by the database.

Request Meaning Success Errors
GET /departments Every department with headcount and average salary 200
POST /departments Create a department 201 + Location 400, 409 duplicate name
DELETE /departments/{id} Delete an empty department 204 404, 409 still has employees
GET /employees?department=&q=&page=&size=&sort= Search, page and sort employees 200 + page 400 bad sort key
GET /employees/{id} One employee 200 404
POST /employees Hire 201 + Location 400, 409 email taken
PUT /employees/{id} Replace details, including a transfer to another department 200 400, 404, 409
POST /employees/{id}/raise Give a raise in percent 200 400, 404
DELETE /employees/{id} Remove an employee 204 404

The business rules:

  • Names are required and at most 50 characters; emails must be well-formed and are unique, ignoring case (they are stored in lowercase).
  • The salary is positive and stored with exactly two decimals. The hire date can't be in the future.
  • An employee must belong to a department that exists. A department can only be deleted when it is empty, and department names are unique, ignoring case.
  • A raise is more than 0% and at most 20%, rounded to the cent with banker's rounding (HALF_EVEN).
  • Two people editing the same employee at once must not silently overwrite each other.

Paging follows Spring's own conventions, because that is what clients of a Spring API will expect: page is zero-based, size defaults to 20 and is capped at 100, and sort=salary,desc may repeat. The response is a page object with content and a page block, which is the stable JSON format Spring Data 3.3+ offers through PagedModel.

Project layout

Generate the project with Spring Initializr (Spring Boot 4, Java 25, Maven) and the dependencies Spring Web, Spring Data JPA, Validation and H2 Database (add the PostgreSQL driver for production). Package by feature:

TEXT
employee-management/
โ”œโ”€โ”€ pom.xml
โ””โ”€โ”€ src/
    โ”œโ”€โ”€ main/
    โ”‚   โ”œโ”€โ”€ java/com/example/hr/
    โ”‚   โ”‚   โ”œโ”€โ”€ HrApplication.java
    โ”‚   โ”‚   โ”œโ”€โ”€ common/
    โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ NotFoundException.java
    โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ ConflictException.java
    โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ InvalidRequestException.java
    โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ ApiExceptionHandler.java
    โ”‚   โ”‚   โ”œโ”€โ”€ department/
    โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ Department.java
    โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ DepartmentRepository.java
    โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ DepartmentStats.java
    โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ DepartmentService.java
    โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ DepartmentController.java
    โ”‚   โ”‚   โ””โ”€โ”€ employee/
    โ”‚   โ”‚       โ”œโ”€โ”€ Employee.java
    โ”‚   โ”‚       โ”œโ”€โ”€ EmployeeRepository.java
    โ”‚   โ”‚       โ”œโ”€โ”€ EmployeeSpecifications.java
    โ”‚   โ”‚       โ”œโ”€โ”€ EmployeeRequest.java
    โ”‚   โ”‚       โ”œโ”€โ”€ EmployeeResponse.java
    โ”‚   โ”‚       โ”œโ”€โ”€ RaiseRequest.java
    โ”‚   โ”‚       โ”œโ”€โ”€ EmployeeService.java
    โ”‚   โ”‚       โ””โ”€โ”€ EmployeeController.java
    โ”‚   โ””โ”€โ”€ resources/application.yml
    โ””โ”€โ”€ test/java/com/example/hr/
        โ””โ”€โ”€ employee/EmployeeServiceTest.java

The employee package depends on department (an employee needs a Department), never the other way around. Keeping the dependency one-directional is what later lets you split the features into separate modules or services (Layered Architecture). DepartmentSummary, the response record for the department list, is nested in DepartmentService.

Configuration

The dependencies are the four starters plus the drivers; Boot's parent manages every version, as in the previous project (Maven in Depth):

XML
<dependencies>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webmvc</artifactId>
  </dependency>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
  </dependency>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
  </dependency>
  <dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
  </dependency>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa-test</artifactId>
    <scope>test</scope>
  </dependency>
</dependencies>
YAML
# src/main/resources/application.yml
spring:
  application:
    name: employee-management
  datasource:
    url: jdbc:h2:mem:hr
  jpa:
    hibernate:
      ddl-auto: create-drop        # Flyway + "validate" in production
    open-in-view: false            # services return finished DTOs
  jackson:
    deserialization:
      fail-on-unknown-properties: true
  data:
    web:
      pageable:
        default-page-size: 20
        max-page-size: 100         # larger requests are silently capped

The last block configures how Spring MVC builds a Pageable from ?page=&size=&sort=. The default maximum is 2,000 rows per page, far too many for a public API. Notice the word capped: Spring doesn't reject size=500, it quietly uses 100. Stage 3 reproduces that behavior.

The entities

Department is small. The unique constraint gets an explicit name, because the error handler will recognize it by that name:

Java
// src/main/java/com/example/hr/department/Department.java
package com.example.hr.department;

import jakarta.persistence.*;

@Entity
@Table(uniqueConstraints = @UniqueConstraint(name = "uk_department_name", columnNames = "name"))
public class Department {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false, length = 60)
    private String name;

    protected Department() {
        // for JPA
    }

    public Department(String name) {
        this.name = name;
    }

    public Long getId() { return id; }
    public String getName() { return name; }
}

Employee owns the relationship. The @ManyToOne is lazy: JPA's default for to-one associations is eager, which means every employee query would also load its department, whether you need it or not. With LAZY, each query decides what to fetch (Fetching Strategies and the N+1 Problem).

Java
// src/main/java/com/example/hr/employee/Employee.java
package com.example.hr.employee;

import com.example.hr.common.InvalidRequestException;
import com.example.hr.department.Department;
import jakarta.persistence.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;

@Entity
@Table(uniqueConstraints = @UniqueConstraint(name = "uk_employee_email", columnNames = "email"),
       indexes = @Index(name = "employee_by_department", columnList = "department_id"))
public class Employee {

    private static final BigDecimal MAX_RAISE_PERCENT = BigDecimal.valueOf(20);

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false, length = 50)
    private String firstName;

    @Column(nullable = false, length = 50)
    private String lastName;

    @Column(nullable = false, length = 120)
    private String email;

    @Column(nullable = false, precision = 10, scale = 2)
    private BigDecimal salary;

    @Column(nullable = false)
    private LocalDate hiredOn;

    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "department_id", foreignKey = @ForeignKey(name = "fk_employee_department"))
    private Department department;

    @Version
    private long version;

    protected Employee() {
        // for JPA
    }

    public Employee(String firstName, String lastName, String email, BigDecimal salary,
                    LocalDate hiredOn, Department department) {
        update(firstName, lastName, email, salary, hiredOn, department);
    }

    public void update(String firstName, String lastName, String email, BigDecimal salary,
                       LocalDate hiredOn, Department department) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
        this.salary = salary.setScale(2, RoundingMode.HALF_EVEN);
        this.hiredOn = hiredOn;
        this.department = department;
    }

    /** Raises are more than 0% and at most 20%, rounded to the cent. */
    public void applyRaise(BigDecimal percent) {
        if (percent.signum() <= 0 || percent.compareTo(MAX_RAISE_PERCENT) > 0) {
            throw new InvalidRequestException("percent", "must be more than 0 and at most 20");
        }
        BigDecimal factor = BigDecimal.ONE.add(percent.movePointLeft(2));
        salary = salary.multiply(factor).setScale(2, RoundingMode.HALF_EVEN);
    }

    public Long getId() { return id; }
    public String getFirstName() { return firstName; }
    public String getLastName() { return lastName; }
    public String getEmail() { return email; }
    public BigDecimal getSalary() { return salary; }
    public LocalDate getHiredOn() { return hiredOn; }
    public Department getDepartment() { return department; }
}

Three design choices are worth a sentence each:

  • No @OneToMany List<Employee> on Department. A bidirectional mapping is tempting, but a department with 5,000 employees would load them all the moment someone touches the list, and both sides must be kept in sync by hand. The relationship is navigated from the employee side, and the department report uses a query instead. Add the collection only when a use case truly needs it.
  • Money is BigDecimal with precision = 10, scale = 2. Never double: 0.1 + 0.2 is not 0.3 in binary floating point.
  • The raise rule lives in the entity, like the "done is final" rule in the previous project. No service, batch job or future endpoint can apply a 50% raise by accident.

Stage 1: the schema and the SQL behind the repositories

Before writing repositories, look at the tables Hibernate creates from these entities and at the SQL each repository method will run. The example below creates the schema (with the same constraint names), loads six employees, and runs the queries that the methods in the next section generate. Run it and keep the output in mind; the rest of the project builds on it.

Java Stage 1: the schema and the SQL behind the repositories

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The join to department in the first query is what @EntityGraph(attributePaths = "department") adds: the departments arrive in the same query, so mapping each employee to a response that includes the department name doesn't trigger one extra SELECT per employee. The second query is the count that a Page needs to report totalElements; Spring Data runs it automatically and skips it when the first page is already smaller than the page size.

The department report uses a LEFT JOIN and GROUP BY, so a department without employees still appears (with a headcount of 0). Finally, the database refuses a duplicate email and refuses to delete a department that employees still reference. Those constraint violations are the safety net under the service's own checks. SQLState class 23 means "integrity constraint violation" in every SQL database, and Spring translates it into DataIntegrityViolationException.

The repositories

Here is the real code that produces those queries. DepartmentRepository adds a case-insensitive existence check and the report query. The report uses a JPQL constructor expression, which creates records directly from the query and never loads Department entities:

Java
// src/main/java/com/example/hr/department/DepartmentRepository.java
package com.example.hr.department;

import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

public interface DepartmentRepository extends JpaRepository<Department, Long> {

    boolean existsByNameIgnoreCase(String name);

    @Query("""
        select new com.example.hr.department.DepartmentStats(d.id, d.name, count(e), avg(e.salary))
        from Department d left join Employee e on e.department = d
        group by d.id, d.name
        order by d.name""")
    List<DepartmentStats> findStats();
}
Java
// src/main/java/com/example/hr/department/DepartmentStats.java
package com.example.hr.department;

/** JPQL's avg() returns Double, and it is null for a department without employees. */
public record DepartmentStats(Long id, String name, Long headcount, Double averageSalary) {}

EmployeeRepository mixes three techniques: derived queries for simple lookups, @EntityGraph to fetch the department in the same query, and JpaSpecificationExecutor for the search with optional filters:

Java
// src/main/java/com/example/hr/employee/EmployeeRepository.java
package com.example.hr.employee;

import java.util.Optional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;

interface EmployeeRepository extends JpaRepository<Employee, Long>, JpaSpecificationExecutor<Employee> {

    Optional<Employee> findByEmail(String email);

    long countByDepartmentId(Long departmentId);

    @Override
    @EntityGraph(attributePaths = "department")
    Optional<Employee> findById(Long id);

    @Override
    @EntityGraph(attributePaths = "department")
    Page<Employee> findAll(Specification<Employee> spec, Pageable pageable);
}

Why specifications? With derived queries, every combination of filters needs its own method: findByDepartmentId, findByLastNameContainingIgnoreCase, findByDepartmentIdAndLastNameContainingIgnoreCase, and so on, doubling with each new filter. A Specification is one reusable WHERE fragment built with the Criteria API (JPQL and the Criteria API), and you combine only the ones the request asked for:

Java
// src/main/java/com/example/hr/employee/EmployeeSpecifications.java
package com.example.hr.employee;

import java.util.Locale;
import org.springframework.data.jpa.domain.Specification;

final class EmployeeSpecifications {

    private EmployeeSpecifications() {
    }

    static Specification<Employee> inDepartment(long departmentId) {
        return (root, query, cb) -> cb.equal(root.get("department").get("id"), departmentId);
    }

    static Specification<Employee> nameContains(String text) {
        String pattern = "%" + text.toLowerCase(Locale.ROOT).replace("\\", "\\\\")
            .replace("%", "\\%").replace("_", "\\_") + "%";
        return (root, query, cb) -> cb.or(
            cb.like(cb.lower(root.get("firstName")), pattern, '\\'),
            cb.like(cb.lower(root.get("lastName")), pattern, '\\'));
    }
}

The LIKE pattern escapes % and _, so a search for 50% looks for that literal text instead of matching everything. Applying an entity graph to a paged query is safe here because department is a to-one association: each employee still produces exactly one row. Fetching a collection with paging is different, and Hibernate would then page in memory with a warning.

DTOs and validation

The requests are records with Bean Validation constraints, and the responses are separate records, so entities never reach Jackson. EmployeeResponse.from reads employee.getDepartment().getName(), which is safe because the service calls it inside its transaction and the department was fetched by the entity graph anyway.

Java
// src/main/java/com/example/hr/employee/EmployeeRequest.java
package com.example.hr.employee;

import jakarta.validation.constraints.*;
import java.math.BigDecimal;
import java.time.LocalDate;

public record EmployeeRequest(
        @NotBlank @Size(max = 50) String firstName,
        @NotBlank @Size(max = 50) String lastName,
        @NotBlank @Email String email,
        @NotNull @Positive BigDecimal salary,
        @NotNull @PastOrPresent LocalDate hiredOn,
        @NotNull Long departmentId) {}
Java
// src/main/java/com/example/hr/employee/RaiseRequest.java
package com.example.hr.employee;

import jakarta.validation.constraints.NotNull;
import java.math.BigDecimal;

public record RaiseRequest(@NotNull BigDecimal percent) {}
Java
// src/main/java/com/example/hr/employee/EmployeeResponse.java
package com.example.hr.employee;

import java.math.BigDecimal;
import java.time.LocalDate;

public record EmployeeResponse(long id, String firstName, String lastName, String email,
                               BigDecimal salary, LocalDate hiredOn, DepartmentRef department) {

    public record DepartmentRef(long id, String name) {}

    static EmployeeResponse from(Employee e) {
        return new EmployeeResponse(e.getId(), e.getFirstName(), e.getLastName(), e.getEmail(),
            e.getSalary(), e.getHiredOn(), new DepartmentRef(e.getDepartment().getId(), e.getDepartment().getName()));
    }
}

Hand-written from methods are fine for a handful of DTOs. Larger codebases often generate them with MapStruct, which writes the same plain code at compile time, with no reflection at run time.

The services

@Transactional on the class gives every public method a transaction; read-only methods say so, which lets Hibernate skip dirty checking for them. The service enforces the rules that need the database: the email check, the department lookup and the "only empty departments can be deleted" rule.

Java
// src/main/java/com/example/hr/employee/EmployeeService.java
package com.example.hr.employee;

import static com.example.hr.employee.EmployeeSpecifications.inDepartment;
import static com.example.hr.employee.EmployeeSpecifications.nameContains;

import com.example.hr.common.ConflictException;
import com.example.hr.common.InvalidRequestException;
import com.example.hr.common.NotFoundException;
import com.example.hr.department.Department;
import com.example.hr.department.DepartmentRepository;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class EmployeeService {

    private final EmployeeRepository employees;
    private final DepartmentRepository departments;

    EmployeeService(EmployeeRepository employees, DepartmentRepository departments) {
        this.employees = employees;
        this.departments = departments;
    }

    public EmployeeResponse hire(EmployeeRequest request) {
        String email = normalize(request.email());
        ensureEmailIsFree(email, null);
        Employee employee = new Employee(request.firstName().strip(), request.lastName().strip(), email,
            request.salary(), request.hiredOn(), department(request.departmentId()));
        return EmployeeResponse.from(employees.saveAndFlush(employee));   // flush: constraint errors surface here
    }

    @Transactional(readOnly = true)
    public EmployeeResponse get(long id) {
        return EmployeeResponse.from(find(id));
    }

    @Transactional(readOnly = true)
    public Page<EmployeeResponse> search(Long departmentId, String text, Pageable pageable) {
        List<Specification<Employee>> filters = new ArrayList<>();
        if (departmentId != null) {
            filters.add(inDepartment(departmentId));
        }
        if (text != null && !text.isBlank()) {
            filters.add(nameContains(text.strip()));
        }
        Pageable stable = PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(),
            pageable.getSort().and(Sort.by("id")));                        // tie-breaker for stable pages
        return employees.findAll(Specification.allOf(filters), stable).map(EmployeeResponse::from);
    }

    public EmployeeResponse update(long id, EmployeeRequest request) {
        Employee employee = find(id);
        String email = normalize(request.email());
        ensureEmailIsFree(email, id);
        employee.update(request.firstName().strip(), request.lastName().strip(), email,
            request.salary(), request.hiredOn(), department(request.departmentId()));
        return EmployeeResponse.from(employee);                            // dirty checking writes it
    }

    public EmployeeResponse raise(long id, RaiseRequest request) {
        Employee employee = find(id);
        employee.applyRaise(request.percent());
        return EmployeeResponse.from(employee);
    }

    public void dismiss(long id) {
        if (!employees.existsById(id)) {
            throw new NotFoundException("Employee " + id + " not found");
        }
        employees.deleteById(id);
    }

    private Employee find(long id) {
        return employees.findById(id).orElseThrow(() -> new NotFoundException("Employee " + id + " not found"));
    }

    private Department department(long id) {
        return departments.findById(id).orElseThrow(() ->
            new InvalidRequestException("departmentId", "department " + id + " does not exist"));
    }

    private void ensureEmailIsFree(String email, Long currentId) {
        employees.findByEmail(email)
            .filter(other -> !other.getId().equals(currentId))
            .ifPresent(other -> {
                throw new ConflictException("Email " + email + " is already used by employee " + other.getId());
            });
    }

    private static String normalize(String email) {
        return email.strip().toLowerCase(Locale.ROOT);
    }
}
Java
// src/main/java/com/example/hr/department/DepartmentService.java
package com.example.hr.department;

import com.example.hr.common.ConflictException;
import com.example.hr.common.NotFoundException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class DepartmentService {

    public record DepartmentSummary(long id, String name, long headcount, BigDecimal averageSalary) {}

    private final DepartmentRepository departments;
    private final JdbcTemplate jdbc;

    DepartmentService(DepartmentRepository departments, JdbcTemplate jdbc) {
        this.departments = departments;
        this.jdbc = jdbc;
    }

    public Department create(String name) {
        String clean = name.strip();
        if (departments.existsByNameIgnoreCase(clean)) {
            throw new ConflictException("Department '" + clean + "' already exists");
        }
        return departments.save(new Department(clean));
    }

    @Transactional(readOnly = true)
    public List<DepartmentSummary> list() {
        return departments.findStats().stream()
            .map(s -> new DepartmentSummary(s.id(), s.name(), s.headcount(), s.averageSalary() == null
                ? BigDecimal.ZERO.setScale(2)
                : BigDecimal.valueOf(s.averageSalary()).setScale(2, RoundingMode.HALF_EVEN)))
            .toList();
    }

    public void delete(long id) {
        if (!departments.existsById(id)) {
            throw new NotFoundException("Department " + id + " not found");
        }
        long headcount = jdbc.queryForObject("select count(*) from employee where department_id = ?", Long.class, id);
        if (headcount > 0) {
            throw new ConflictException("Department " + id + " still has " + headcount
                + (headcount == 1 ? " employee" : " employees") + "; move them first");
        }
        departments.deleteById(id);
    }
}

DepartmentService counts employees with a one-line JdbcTemplate query instead of calling EmployeeRepository. That keeps the dependency pointing in one direction (department doesn't know about the employee package) and shows that JPA and plain SQL mix freely in one transaction; Spring binds both to the same connection. Spring JDBC with JdbcTemplate and JdbcClient covers that API. An alternative is a domain event ("department deleting") that the employee feature answers.

ensureEmailIsFree checks first and inserts afterwards. Two requests with the same new email can both pass the check before either inserts. The unique constraint uk_employee_email catches that race, and saveAndFlush makes the INSERT run inside hire, so the DataIntegrityViolationException is raised there instead of at commit. The error handler turns it into a 409. Always pair a "check first" rule with a database constraint.

Stage 2: what Spring Data, Bean Validation and @Transactional do

The second stage is the same back end without Spring, so you can watch the machinery work. Each piece is named after the Spring feature it imitates:

  • Constraint annotations and validate: real runtime annotations on record components, read with reflection. This is, in miniature, what Hibernate Validator does when @Valid is on a parameter: it checks every constraint and reports all violations, not just the first. (The email check is simpler than Hibernate Validator's.)
  • TransactionTemplate: opens one connection, turns off auto-commit, and binds the connection to the current thread with a ThreadLocal. Repositories ask for "the current connection", so all SQL in one service call shares one transaction. A runtime exception rolls everything back. Spring's @Transactional works the same way, through TransactionSynchronizationManager, and Spring even has a class with this name and these two methods for programmatic transactions.
  • Jdbc: a pocket JdbcTemplate with exception translation: SQLState 23xxx becomes DataIntegrityViolationException with the constraint's name.
  • EmployeeRepository.save: an INSERT for new entities, and an UPDATE ... WHERE id = ? AND version = ? for existing ones, throwing OptimisticLockingFailureException when no row matches. That is precisely what @Version makes Hibernate do.
  • findAll(departmentId, nameContains, pageRequest): the specification search, building only the WHERE conditions that were asked for, with the sort whitelist and the id tie-breaker.

The main method then drives the services directly and prints what each call returns.

Java Stage 2: entities, repositories, validation and services

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Read the output from top to bottom. The Engineering page is sorted by salary, highest first. The search for son matches Jackson and Johnson, case-insensitively. The 7.5% raise for Alan Turing gives 91500.00 ร— 1.075 = 98362.50. The transfer of Carl Johnson to Finance is just an update of department_id, and the department summaries immediately reflect it, including Sales' new average.

The rule checks show the layering. All four invalid fields come back together, sorted by name, before any SQL runs. The duplicate email is caught although it is written in capitals, because the service lowercases before checking. The unknown department is reported as a field error (departmentId), not a 404: the URL was fine, the request body pointed at something that doesn't exist. And Sales can't be deleted while Mary Jackson still works there.

The service's hire catches DataIntegrityViolationException for uk_employee_email and turns it into a ConflictException. In the Spring version, that translation sits in the @RestControllerAdvice instead, so every endpoint benefits. Either way, the database message never reaches the client: it would reveal table and index names.

The controllers

The controllers are thin. Spring MVC builds the Pageable from page, size and sort, and PagedModel turns a Page into the stable JSON format shown in the contract. The sort keys are still checked against a whitelist: Spring Data would accept sort=email or sort=version because they are real properties, but they are not part of the public contract (and sorting by an unindexed column on a big table is a performance problem).

Java
// src/main/java/com/example/hr/employee/EmployeeController.java
package com.example.hr.employee;

import java.net.URI;
import java.util.Set;
import jakarta.validation.Valid;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PagedModel;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;

@RestController
@RequestMapping("/employees")
class EmployeeController {

    private static final Set<String> SORTABLE = Set.of("id", "firstName", "lastName", "salary", "hiredOn");

    private final EmployeeService service;

    EmployeeController(EmployeeService service) {
        this.service = service;
    }

    @GetMapping
    PagedModel<EmployeeResponse> search(@RequestParam(required = false) Long department,
                                        @RequestParam(required = false) String q,
                                        Pageable pageable) {
        pageable.getSort().forEach(order -> {
            if (!SORTABLE.contains(order.getProperty())) {
                throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Cannot sort by '" + order.getProperty() + "'");
            }
        });
        return new PagedModel<>(service.search(department, q, pageable));
    }

    @GetMapping("/{id}")
    EmployeeResponse get(@PathVariable long id) {
        return service.get(id);
    }

    @PostMapping
    ResponseEntity<EmployeeResponse> hire(@Valid @RequestBody EmployeeRequest request) {
        EmployeeResponse employee = service.hire(request);
        return ResponseEntity.created(URI.create("/employees/" + employee.id())).body(employee);
    }

    @PutMapping("/{id}")
    EmployeeResponse update(@PathVariable long id, @Valid @RequestBody EmployeeRequest request) {
        return service.update(id, request);
    }

    @PostMapping("/{id}/raise")
    EmployeeResponse raise(@PathVariable long id, @Valid @RequestBody RaiseRequest request) {
        return service.raise(id, request);
    }

    @DeleteMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    void dismiss(@PathVariable long id) {
        service.dismiss(id);
    }
}

The raise is POST /employees/{id}/raise, not a PUT of a new salary. It is a business action with its own rule, and modeling it as its own endpoint keeps the rule on the server; clients can't compute a salary and send it. See REST API Design for when actions deserve their own resources.

DepartmentController follows the same pattern with three methods (GET, POST returning 201 with a Location, DELETE returning 204). The error handler extends ResponseEntityExceptionHandler exactly as in Project: Task API with Spring Boot; the new part is translating the database's safety net:

Java
// in src/main/java/com/example/hr/common/ApiExceptionHandler.java
@ExceptionHandler(DataIntegrityViolationException.class)
ProblemDetail constraintViolated(DataIntegrityViolationException e) {
    String message = String.valueOf(e.getMostSpecificCause().getMessage()).toLowerCase(Locale.ROOT);
    String detail = message.contains("uk_employee_email") ? "This email is already used by another employee"
        : message.contains("uk_department_name") ? "A department with this name already exists"
        : "The request conflicts with existing data";
    return ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT, detail);
}

@ExceptionHandler(ObjectOptimisticLockingFailureException.class)
ProblemDetail staleUpdate(ObjectOptimisticLockingFailureException e) {
    return ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT,
        "The employee was changed by someone else; reload and try again");
}

Matching on the constraint name in the database message is pragmatic and common, and it is why the constraints got explicit names in the entities. Never copy the raw message into the response.

Stage 3: the HTTP API

The third stage puts the services from Stage 2 behind HTTP. The web layer imitates what Spring MVC does around the controllers: Request.id() is @PathVariable, param is @RequestParam, pageable() is the Pageable argument resolver (zero-based pages, a default size of 20, a silent cap at 100, repeated sort parameters, and bad paging numbers ignored rather than rejected), body is @RequestBody with the 415 and unknown-field checks, and toProblem is the @RestControllerAdvice. A client script at the end calls every route.

Java Stage 3: controllers, paging parameters and problem details over HTTP

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Connect each response to the code that produced it:

  • POST /departments answers 201 with Location: /departments/4.
  • The paged search returns the two best-paid engineers, and the page block says there are 3 matches in 2 pages. The departments are embedded as {"id":1,"name":"Engineering"} without any extra query, thanks to the join.
  • Hiring Katherine Johnson with [email protected] stores [email protected], and the salary 88000 comes back as 88000.00: the scale is part of the contract.
  • After the raise and the dismissal of Hedy Lamarr, GET /departments shows Finance with a headcount of 0 and an average of 0.00, and the new Research department with one employee.
  • The errors are all application/problem+json: four field errors at once, the case-insensitive email conflict, the unknown field manager (rejected because fail-on-unknown-properties is on), the 30% raise, the non-empty department, a sort key outside the whitelist, and a missing employee.

Spring's Pageable resolver is lenient on purpose: ?page=abc or ?size=-3 fall back to the defaults, and ?size=500 becomes 100. That is friendly for browsers and a surprise for API clients, which is why the response always reports the size it actually used. If your API should reject bad paging values with 400 instead, bind page and size with @RequestParam and @Min/@Max, as the previous project did.

Stage 4: tests

In the real project, the most valuable tests run the services against a real database: they check the business rules, the queries, the constraints and the transactions together. Spring Boot's @DataJpaTest starts only JPA and an embedded database, and @Import adds the services:

Java
// src/test/java/com/example/hr/employee/EmployeeServiceTest.java
package com.example.hr.employee;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

import com.example.hr.common.ConflictException;
import com.example.hr.department.DepartmentService;
import java.math.BigDecimal;
import java.time.LocalDate;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest;
import org.springframework.context.annotation.Import;

@DataJpaTest
@Import({EmployeeService.class, DepartmentService.class})
class EmployeeServiceTest {

    @Autowired EmployeeService employees;
    @Autowired DepartmentService departments;
    long engineering;

    @BeforeEach
    void createDepartment() {
        engineering = departments.create("Engineering").getId();
    }

    @Test
    void emailsAreUniqueIgnoringCase() {
        employees.hire(new EmployeeRequest("Ada", "Lovelace", "[email protected]",
            new BigDecimal("98000"), LocalDate.of(2024, 2, 1), engineering));

        assertThatThrownBy(() -> employees.hire(new EmployeeRequest("Ada", "Byron", "[email protected]",
                new BigDecimal("50000"), LocalDate.of(2024, 2, 1), engineering)))
            .isInstanceOf(ConflictException.class);
    }

    @Test
    void raisesAreRoundedToCents() {
        long id = employees.hire(new EmployeeRequest("Mary", "Jackson", "[email protected]",
            new BigDecimal("4999.99"), LocalDate.of(2024, 2, 1), engineering)).id();

        assertThat(employees.raise(id, new RaiseRequest(new BigDecimal("7"))).salary())
            .isEqualByComparingTo("5349.99");
    }
}

@DataJpaTest wraps each test in a transaction that is rolled back afterwards, so tests don't see each other's rows. DepartmentService needs a JdbcTemplate, which @DataJpaTest also auto-configures. A @WebMvcTest for the controllers and the error format completes the picture, exactly as in the previous project; Testing Spring Boot Applications covers both.

The runnable version gives every test its own fresh H2 database (instead of a rollback) and runs twelve tests with JUnit. Two of them test the infrastructure you built in Stage 2: a stale update is refused by the version check, and an exception thrown after an UPDATE rolls the whole transaction back.

Java Stage 4: JUnit tests for the services on a real database

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

All twelve tests pass. Look at aStaleUpdateIsRejected: HR and payroll load the same employee at version 0; HR saves first (version becomes 1), so payroll's UPDATE ... WHERE version = 0 matches no row and the salary change is refused instead of silently undoing HR's edit. pagesUseTheIdAsATieBreaker shows why the service adds Sort.by("id"): four employees share the salary 50,000, and without a unique last sort key the database may return them in a different order for page 0 and page 1, so a row could appear on both pages or on neither.

Running the real application

With the project on your machine (these commands are read-only here):

Terminal
./mvnw spring-boot:run

curl -i -X POST localhost:8080/departments -H "Content-Type: application/json" -d '{"name": "Engineering"}'
curl -i -X POST localhost:8080/employees -H "Content-Type: application/json" \
     -d '{"firstName": "Ada", "lastName": "Lovelace", "email": "[email protected]",
          "salary": 98000, "hiredOn": "2019-03-04", "departmentId": 1}'
curl "localhost:8080/employees?department=1&sort=salary,desc&size=2"
curl -X POST localhost:8080/employees/1/raise -H "Content-Type: application/json" -d '{"percent": 7.5}'
curl localhost:8080/departments

./mvnw test

Keep logging.level.org.hibernate.SQL=debug on while you try it, and compare the logged SQL with Stage 1. You should see one select ... left join department per page plus one count, never a query per employee.

Design decisions in review

  • Two aggregates, one direction. Employee references Department; Department knows nothing about employees. Reports use queries, not collections.
  • Lazy by default, fetch on purpose. Every @ManyToOne is LAZY, and the queries that need the department say so with @EntityGraph.
  • Specifications for optional filters, derived queries for fixed lookups, @Query with a constructor expression for reports.
  • DTOs on both sides. Requests carry the validation constraints; responses decide the JSON; entities stay internal.
  • Rules in three places, each for a reason. Format rules in annotations, rules that need data in the service, invariants in the entity, and a database constraint under the rules that a race could break.
  • Stable paging. A whitelist of sort keys, an id tie-breaker, a page-size cap, and PagedModel for a JSON format you control.
  • Optimistic locking with @Version for concurrent edits.

Ideas for extending the project

  • Managers. Add @ManyToOne Employee manager and a rule that a manager must work in the same department. Then write a recursive query (WITH RECURSIVE) that lists everyone under a manager.
  • Salary history. Record every raise in a salary_change table in the same transaction, and add GET /employees/{id}/salary-history with paging.
  • Auditing. Add @CreatedDate, @LastModifiedDate and @CreatedBy with Spring Data's auditing (Spring Data JPA).
  • Bulk raise. POST /departments/{id}/raise for everyone in a department, first entity by entity, then as one @Modifying update, and compare the SQL (Hibernate's Native API: Session, HQL and Native SQL explains batch settings).
  • Security. Only users with the HR role may see salaries; others get a smaller DTO (Spring Security).
  • PostgreSQL and Flyway. Move the schema from Stage 1 into V1__init.sql, run PostgreSQL with Docker Compose and Testcontainers (Docker for Java Developers).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is the department search implemented with specifications instead of derived query methods?

    findByDepartmentId, findByLastNameContaining and findByDepartmentIdAndLastNameContaining already cover two filters; a third filter would need eight methods. Specifications are composable WHERE fragments.
  2. 2. A client calls GET /employees?size=500, and max-page-size is 100. What does Spring's Pageable resolver do?

    The resolver silently caps the size at max-page-size. Use @RequestParam with @Max if you want to reject large sizes instead.
  3. 3. The service checks that an email is free and then inserts the employee. Why is the unique constraint uk_employee_email still needed?

    Check-then-act is a race. The constraint is the safety net, and saveAndFlush makes the violation surface inside hire, where it is translated into a 409.
  4. 4. Four employees earn 50,000. The query sorts only by salary desc and uses OFFSET paging. What can go wrong?

    SQL guarantees no order among rows with equal sort keys. Adding a unique tie-breaker such as id makes every page deterministic.
  5. 5. Why does Employee have no @OneToMany List<Employee> back on Department?

    Map relationships for the navigation your use cases need. The department report needs counts and averages, which a GROUP BY query produces without loading any employees.

Summary

  • Two related entities bring in the everyday Spring Data JPA problems: fetching, optional filters, paging, reports, uniqueness and concurrency.
  • Map @ManyToOne as lazy and fetch it with @EntityGraph where a query needs it; avoid collections nobody uses.
  • Use derived queries for fixed lookups, specifications for optional filters, and a JPQL constructor expression (or a JdbcTemplate query) for reports.
  • Validate format with Bean Validation on request records, check data-dependent rules in the transactional service, keep invariants in the entity, and back race-prone rules with named database constraints.
  • Read Pageable from the URL, whitelist sort keys, add an id tie-breaker, cap the page size, and return PagedModel.
  • @Version turns lost updates into 409 Conflict; @Transactional rolls back on runtime exceptions.
  • Test services against a real database with @DataJpaTest; the runnable stages show what each Spring feature does underneath.

Next: Project: Task Management Microservices