java 43 lines · 7 steps

How a Spring REST controller maps users

A Spring controller exposes read endpoints that fetch users and convert entities into a clean response record.

Explained by highlit
1@RestController
2@RequestMapping("/api/users")
3public class UserController {
4 
5 private final UserRepository userRepository;
6 
7 public UserController(UserRepository userRepository) {
8 this.userRepository = userRepository;
9 }
10 
11 @GetMapping("/{id}")
12 public ResponseEntity<UserResponse> getUser(@PathVariable Long id) {
13 return userRepository.findById(id)
14 .map(this::toResponse)
15 .map(ResponseEntity::ok)
16 .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "User not found"));
17 }
18 
19 @GetMapping
20 public List<UserResponse> listUsers() {
21 return userRepository.findAll().stream()
22 .map(this::toResponse)
23 .toList();
24 }
25 
26 private UserResponse toResponse(User user) {
27 return new UserResponse(
28 user.getId(),
29 user.getFullName(),
30 user.getEmail(),
31 user.getRole().name(),
32 user.getCreatedAt()
33 );
34 }
35 
36 public record UserResponse(
37 Long id,
38 String fullName,
39 String email,
40 String role,
41 Instant createdAt
42 ) {}
43}
01 / 01
STEP 01

Walkthrough

Space play ←→ step click any line
Three takeaways
  1. 1Mapping entities to a dedicated response type keeps your API contract decoupled from your database schema.
  2. 2Chaining Optional's map and orElseThrow turns a missing lookup into a clean HTTP error without null checks.
  3. 3Constructor injection of a repository makes controllers easy to test and their dependencies explicit.

Related explainers

typescript
import { registerLocaleData } from '@angular/common';
import localeFr from '@angular/common/locales/fr';
import localeFrExtra from '@angular/common/locales/extra/fr';
import localeDe from '@angular/common/locales/de';

Locale-aware bootstrapping in Angular

i18n localization dependency-injection
Intermediate 8 steps
typescript
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import * as Joi from 'joi';
 

Validating env config at boot in NestJS

configuration schema-validation environment-variables
Intermediate 8 steps
java
@Component
@Converter
public class EncryptedStringConverter implements AttributeConverter<String, String> {
 

Transparent column encryption in Spring & JPA

encryption aes-gcm jpa-converter
Advanced 10 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Cache } from 'cache-manager';
import { InjectRepository } from '@nestjs/typeorm';

A cache-aside country lookup in NestJS

cache-aside dependency-injection batch-lookup
Intermediate 8 steps
java
package com.acme.billing.config;
 
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;

Feature-flagged beans with Spring @ConditionalOnProperty

feature-flags conditional-beans strategy-pattern
Intermediate 5 steps
typescript
import { Injectable, effect, signal, computed } from '@angular/core';
 
interface Preferences {
  theme: 'light' | 'dark';

A signal-based preferences store in Angular

signals state-management persistence
Intermediate 7 steps

Share this explainer

Here's the card — post it anywhere.

How a Spring REST controller maps users — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code