Chapter 8: "What is...?" — The 40 Most Asked Interview Concepts
This chapter gathers questions like "What is a DTO?", "What is MVC?" — the vocabulary and concept questions that every interviewer asks first. If you can only review one chapter, this is the one.
1. What is a DTO (Data Transfer Object)?
A DTO is a simple object used to transport data between application layers, without business logic.
Why not use the Entity directly?
| Entity | DTO |
|---|---|
| Mapped to the database | Just a data container |
| Contains JPA relations (lazy loading) | Contains only necessary fields |
| Can expose sensitive data (password, role) | We choose exactly what to expose |
| Changing the DB = changing the API | API independent of the DB |
Concrete example
// ENTITY (linked to the DB)
@Entity
public class User {
@Id @GeneratedValue
private Long id;
private String name;
private String email;
private String password; // ← should NEVER be exposed!
private String role;
@OneToMany(mappedBy = "user")
private List<Order> orders; // ← lazy loading, can cause N+1
}
// DTO (what the client receives)
public record UserDTO(
Long id,
String name,
String email
// no password, no role, no orders
) {}
// Conversion in the Service
@Service
public class UserService {
public UserDTO toDto(User user) {
return new UserDTO(user.getId(), user.getName(), user.getEmail());
}
}
"A DTO is a simple object used to transfer data between layers. I use DTOs to avoid exposing JPA entities in the API — this prevents leaking sensitive fields like passwords and avoids lazy-loading issues."
2. What is MVC (Model-View-Controller)?
An architectural pattern that separates the application into 3 responsibilities:
| Component | Role | In Spring Boot |
|---|---|---|
| Model | Data and business logic | Entity, Service, Repository |
| View | Display (what the user sees) | JSON (REST API) or Thymeleaf (HTML) |
| Controller | The orchestrator that receives requests and coordinates | @Controller or @RestController |
In Spring Boot REST, the "View" is the JSON
@RestController // Controller
@RequestMapping("/api/users")
public class UserController {
@GetMapping("/{id}")
public UserDTO getUser(@PathVariable Long id) {
return userService.findById(id); // Model → converted to JSON (View)
}
}
"MVC separates the application into Model (data/logic), View (presentation), and Controller (request handling). In a REST API, the View is the JSON response automatically serialized by Jackson."
3. What is a REST API?
API = Application Programming Interface (interface for two programs to communicate)
REST = Representational State Transfer (architectural style for web APIs)
The 6 REST rules
| Rule | Meaning |
|---|---|
| Client-Server | The client and server are separate |
| Stateless | Each request contains all necessary information |
| Cache | Responses can be cached |
| Uniform Interface | Consistent URLs, standard HTTP methods |
| Layered System | The client doesn't know if it's talking to the final server |
| Code on Demand (optional) | The server can send executable code |
HTTP methods
| Method | Action | Example | Return code |
|---|---|---|---|
| GET | Read | GET /api/users/1 | 200 OK |
| POST | Create | POST /api/users | 201 Created |
| PUT | Replace entirely | PUT /api/users/1 | 200 OK |
| PATCH | Modify partially | PATCH /api/users/1 | 200 OK |
| DELETE | Delete | DELETE /api/users/1 | 204 No Content |
"REST is an architectural style for web APIs. It uses HTTP methods (GET, POST, PUT, DELETE) to perform CRUD operations on resources identified by URLs. It's stateless — each request is independent."
4. What is CRUD?
The 4 basic operations on data:
| Letter | Operation | SQL | HTTP | Spring Data |
|---|---|---|---|---|
| C | Create | INSERT | POST | save() |
| R | Read | SELECT | GET | findById(), findAll() |
| U | Update | UPDATE | PUT/PATCH | save() |
| D | Delete | DELETE | DELETE | deleteById() |
5. What is a POJO?
POJO = Plain Old Java Object
A simple Java object, without any dependency on a framework:
// This is a POJO — just fields, getters, setters
public class User {
private String name;
private String email;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
}
A Java Bean is a POJO that follows conventions: no-argument constructor, getters/setters, serializable.
A Spring Bean is an object managed by the Spring container (can be a POJO annotated @Component, @Service, etc.).
6. What is a Spring Bean?
An object created and managed by the Spring container (ApplicationContext).
// This is a Spring Bean — Spring creates and manages it
@Service
public class UserService {
// Spring automatically instantiates it at startup
// Spring injects it where needed
// Spring manages its lifecycle
}
// This is NOT a Bean — created manually
UserService service = new UserService();
How to create a Bean?
| Method | Example |
|---|---|
| Stereotype annotations | @Component, @Service, @Repository, @Controller |
| @Bean in @Configuration | Method that returns an object |
| @Import | Import a configuration class |
"A Spring Bean is an object managed by the Spring IoC container. Spring creates it, injects its dependencies, and manages its lifecycle. By default, beans are singletons."
7. What is IoC (Inversion of Control)?
Without IoC: the code creates its own dependencies.
With IoC: the container creates the dependencies and provides them to the code.
// WITHOUT IoC — the code controls creation
public class OrderService {
private UserRepository repo = new UserRepository(); // Creates itself
private EmailService email = new EmailService(); // Creates itself
}
// WITH IoC — Spring controls creation
@Service
public class OrderService {
private final UserRepository repo; // Provided by Spring
private final EmailService email; // Provided by Spring
public OrderService(UserRepository repo, EmailService email) {
this.repo = repo; // Injected by Spring
this.email = email; // Injected by Spring
}
}
Dependency Injection (DI) is the concrete mechanism that implements IoC.
8. What is ORM and JPA and Hibernate?
| Term | Definition | Analogy |
|---|---|---|
| ORM | Object-Relational Mapping — technique that maps Java objects to SQL tables | The translator between Java and SQL |
| JPA | Jakarta Persistence API — the specification (interface) of ORM in Java | The contract / the standard |
| Hibernate | The most popular implementation of JPA | The software that does the work |
JPA (specification) → Hibernate (implementation)
↓ ↓
"here's how it should "here's the code that
work" makes it work"
// JPA Annotations (standard)
@Entity // JPA says: "this class is an entity"
@Table(name = "users") // JPA says: "mapped to the users table"
public class User {
@Id // JPA says: "this is the primary key"
@GeneratedValue // JPA says: "auto-incremented"
private Long id;
@Column(name = "full_name") // JPA says: "mapped to this column"
private String name;
}
// Hibernate does the work behind: generates SQL queries,
// manages cache, lazy loading, transactions...
"JPA is the specification that defines how Java objects map to database tables. Hibernate is the most popular implementation of JPA. I use JPA annotations so my code isn't tied to Hibernate specifically."
9. What is Maven?
A build and dependency management tool for Java projects.
| Feature | Description |
|---|---|
| Dependencies | Automatically downloads libraries (from Maven Central) |
| Build | Compiles, tests, packages the application (.jar) |
| Lifecycle | mvn clean → mvn compile → mvn test → mvn package |
| pom.xml | The project's configuration file |
<!-- pom.xml — the heart of Maven -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
Maven vs Gradle: Maven uses XML (verbose but standard), Gradle uses Groovy/Kotlin (more concise but learning curve).
10. What is Tomcat?
A web server / servlet container that runs Java applications.
Spring Boot embeds Tomcat directly:
java -jar myapp.jar
↓
┌──────────────────────┐
│ Spring Boot │
│ ┌──────────────────┐ │
│ │ Embedded Tomcat │ │ ← listens on port 8080
│ │ (embedded) │ │
│ └──────────────────┘ │
│ ┌──────────────────┐ │
│ │ Your code │ │
│ │ Controllers │ │
│ │ Services │ │
│ └──────────────────┘ │
└──────────────────────┘
No need to install Tomcat separately — Spring Boot embeds it in the .jar.
11. What is JSON?
JSON = JavaScript Object Notation — a lightweight and readable data format.
{
"id": 1,
"name": "John Doe",
"email": "john@mail.com",
"active": true,
"roles": ["USER", "ADMIN"],
"address": {
"city": "Montreal",
"postalCode": "H2X 1Y4"
}
}
In Spring Boot, Jackson automatically converts Java objects to JSON and vice versa:
// Java → JSON (serialization)
@GetMapping("/users/1")
public UserDTO getUser() {
return new UserDTO(1L, "John", "john@mail.com");
// Jackson automatically transforms to JSON
}
// JSON → Java (deserialization)
@PostMapping("/users")
public void create(@RequestBody UserDTO dto) {
// Jackson transforms the JSON body into a UserDTO object
}
12. What is Postman and Swagger?
| Tool | Role |
|---|---|
| Postman | HTTP client to manually test REST APIs (send GET, POST, etc.) |
| Swagger / OpenAPI | Automatically generates an interactive documentation of the API |
Swagger in Spring Boot:
<!-- Add to pom.xml -->
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.3.0</version>
</dependency>
Then, access http://localhost:8080/swagger-ui.html to test your endpoints directly from the browser.
13. What is Docker?
Docker creates containers: isolated environments that contain your application + all its dependencies.
Without Docker: With Docker:
"It works on my machine" "It works EVERYWHERE"
My PC: Container:
├── Java 17 ├── Java 17
├── Maven 3.9 ├── Maven 3.9
├── PostgreSQL 15 ├── App.jar
└── My App └── (everything included)
↕ Possible conflicts ↕ Isolated and portable
# Dockerfile for Spring Boot
FROM eclipse-temurin:17-jre
COPY target/app.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]
14. What is CI/CD?
| Term | Meaning | When |
|---|---|---|
| CI — Continuous Integration | Automatically compile + test on each git push | On each commit |
| CD — Continuous Delivery | Automatically deploy to production | After tests |
Tools: GitHub Actions, Jenkins, GitLab CI, CircleCI.
15. What is Git and GitHub?
| Term | Definition |
|---|---|
| Git | Version control tool — tracks code change history |
| GitHub | Web platform that hosts Git repositories + collaboration |
git add . # Stage changes
git commit -m "fix" # Record in local history
git push origin main # Push to GitHub
git pull # Fetch changes from others
git branch feature-x # Create a branch
git merge feature-x # Merge a branch
16. What is Layered Architecture?
Golden Rule
Each layer only communicates with the layer directly below it.
✅ Controller → Service → Repository → Database
❌ Controller → Repository (never directly!)
❌ Controller → Database (never directly!)
"I follow a layered architecture: Controller handles HTTP, Service contains business logic, Repository handles data access. Each layer only talks to the layer directly below it. This separation makes the code testable and maintainable."
17. What is the Spring IoC Container (ApplicationContext)?
The container that creates, configures, and assembles all Spring beans at startup:
Application startup:
1. @SpringBootApplication → starts the scan
2. Finds @Component, @Service, @Repository, @Controller
3. Creates instances (beans)
4. Resolves dependencies (@Autowired)
5. Injects dependencies
6. Calls @PostConstruct
7. ══════ Application ready ══════
18. What is @Autowired? What is dependency injection?
3 ways to inject in Spring:
// ✅ 1. CONSTRUCTOR Injection (recommended)
@Service
public class OrderService {
private final UserRepository userRepo;
private final EmailService emailService;
public OrderService(UserRepository userRepo, EmailService emailService) {
this.userRepo = userRepo;
this.emailService = emailService;
}
}
// ⚠️ 2. SETTER Injection
@Service
public class OrderService {
private UserRepository userRepo;
@Autowired
public void setUserRepo(UserRepository userRepo) {
this.userRepo = userRepo;
}
}
// ❌ 3. FIELD Injection (discouraged)
@Service
public class OrderService {
@Autowired
private UserRepository userRepo;
}
Why is the constructor the best?
| Criterion | Constructor | Setter | Field |
|---|---|---|---|
Immutability (final) | ✅ | ❌ | ❌ |
| Testable without Spring | ✅ | ⚠️ | ❌ |
| Mandatory dependencies | ✅ | ❌ | ❌ |
| Detects circular dependencies | ✅ | ❌ | ❌ |
"I prefer constructor injection because it allows final fields (immutability), makes dependencies explicit, and works without Spring for testing. Since Spring 4.3, @Autowired is optional on a single constructor."
19. What is a Java Record?
A Record (Java 16+) is a special type for immutable objects that only contain data:
// Before (classic POJO — 30 lines)
public class UserDTO {
private final Long id;
private final String name;
private final String email;
public UserDTO(Long id, String name, String email) {
this.id = id; this.name = name; this.email = email;
}
public Long getId() { return id; }
public String getName() { return name; }
public String getEmail() { return email; }
// + equals(), hashCode(), toString()...
}
// After (Record — 1 line!)
public record UserDTO(Long id, String name, String email) {}
// Automatically generates: constructor, getters, equals, hashCode, toString
Ideal for: DTOs, requests, responses, events.
20. What is Lombok?
A library that automatically generates repetitive code (boilerplate) at compile time:
// Without Lombok — 50+ lines
public class User {
private Long id;
private String name;
private String email;
// constructor, getters, setters, equals, hashCode, toString...
}
// With Lombok — 5 lines
@Data // getters, setters, equals, hashCode, toString
@NoArgsConstructor // no-argument constructor
@AllArgsConstructor // all-arguments constructor
@Builder // Builder pattern
public class User {
private Long id;
private String name;
private String email;
}
| Lombok Annotation | Generates |
|---|---|
@Getter / @Setter | Getters and/or setters |
@ToString | toString() |
@EqualsAndHashCode | equals() and hashCode() |
@Data | Everything above |
@Builder | Builder pattern |
@NoArgsConstructor | No-argument constructor |
@AllArgsConstructor | All-arguments constructor |
@Slf4j | Logger log |
21. What is ResponseEntity?
A Spring object that represents the complete HTTP response (status + headers + body):
// Without ResponseEntity — no control over status
@GetMapping("/{id}")
public UserDTO getUser(@PathVariable Long id) {
return userService.findById(id); // always 200 OK
}
// With ResponseEntity — full control
@GetMapping("/{id}")
public ResponseEntity<UserDTO> getUser(@PathVariable Long id) {
return userService.findById(id)
.map(ResponseEntity::ok) // 200 OK
.orElse(ResponseEntity.notFound().build()); // 404 Not Found
}
@PostMapping
public ResponseEntity<UserDTO> create(@Valid @RequestBody CreateUserRequest req) {
UserDTO created = userService.create(req);
return ResponseEntity
.status(HttpStatus.CREATED) // 201 Created
.header("Location", "/api/users/" + created.id())
.body(created);
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> delete(@PathVariable Long id) {
userService.delete(id);
return ResponseEntity.noContent().build(); // 204 No Content
}
22. What is @Valid and Bean Validation?
// DTO with validation constraints
public record CreateUserRequest(
@NotBlank(message = "Name is required")
String name,
@Email(message = "Invalid email")
@NotBlank
String email,
@Size(min = 8, message = "Minimum 8 characters")
String password,
@Min(value = 18, message = "Minimum 18 years")
int age
) {}
// Controller — @Valid triggers validation
@PostMapping
public ResponseEntity<UserDTO> create(@Valid @RequestBody CreateUserRequest req) {
// If validation fails → 400 Bad Request automatically
return ResponseEntity.status(HttpStatus.CREATED)
.body(userService.create(req));
}
| Annotation | Checks |
|---|---|
@NotNull | Not null |
@NotBlank | Not null, not empty, not just spaces |
@NotEmpty | Not null, not empty |
@Email | Valid email format |
@Size(min, max) | Size between min and max |
@Min / @Max | Numeric min/max value |
@Pattern(regexp) | Matches a regular expression |
@Past / @Future | Date in the past/future |
23. What is application.properties / application.yml?
The configuration file for the Spring Boot application:
# application.yml
server:
port: 8080
spring:
datasource:
url: jdbc:postgresql://localhost:5432/mydb
username: admin
password: secret
jpa:
hibernate:
ddl-auto: update
show-sql: true
app:
jwt:
secret: mySecretKey
expiration: 86400000
Access values with @Value:
@Value("${app.jwt.secret}")
private String jwtSecret;
@Value("${server.port}")
private int port;
24. What is Spring Security?
The Spring security framework for authentication and authorization:
| Concept | Question | Example |
|---|---|---|
| Authentication | "Who are you?" | Login + password, JWT |
| Authorization | "Do you have permission?" | USER, ADMIN role |
25. What is JWT (JSON Web Token)?
A token sent in each request to prove the user's identity:
JWT = HEADER.PAYLOAD.SIGNATURE
eyJhbGciOiJIUzI1NiJ9. ← Header (algorithm)
eyJzdWIiOiJhbGljZSJ9. ← Payload (data: user, role, expiration)
SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c ← Signature (verification)
The flow
1. POST /api/auth/login { "email": "alice@mail.com", "password": "123" }
2. Server verifies → Generates a JWT → Returns it to the client
3. Client stores the JWT
4. GET /api/users Header: Authorization: Bearer eyJhbG...
5. Server validates the JWT → Authorizes the request
26. What is CORS?
CORS = Cross-Origin Resource Sharing
When your frontend (localhost:3000) calls your backend (localhost:8080), the browser blocks the request for security. CORS allows these cross-origin requests.
@Configuration
public class CorsConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("http://localhost:3000")
.allowedMethods("GET", "POST", "PUT", "DELETE");
}
};
}
}
27. What is Singleton in Spring?
By default, each Spring bean is a Singleton — a single instance shared throughout the application:
@Service
public class UserService { ... } // ONE single instance, shared everywhere
// Everywhere in the app, it's the SAME UserService object
@RestController
class UserController {
private final UserService userService; // same instance
}
@RestController
class AdminController {
private final UserService userService; // same instance!
}
28. What is the difference between PUT and PATCH?
| Method | Action | Example |
|---|---|---|
| PUT | Replaces all of the object | Send all fields |
| PATCH | Modifies partially | Send only fields to modify |
// PUT — replaces everything
@PutMapping("/{id}")
public UserDTO update(@PathVariable Long id, @RequestBody UserDTO dto) {
// All fields are overwritten
}
// PATCH — modifies partially
@PatchMapping("/{id}")
public UserDTO patch(@PathVariable Long id, @RequestBody Map<String, Object> updates) {
// Only sent fields are modified
}
29. What is a Custom Exception?
// Custom exception
@ResponseStatus(HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
public ResourceNotFoundException(String message) {
super(message);
}
}
// Usage
public User findById(Long id) {
return userRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("User not found: " + id));
}
// Global handling
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<ErrorResponse> handleNotFound(ResourceNotFoundException ex) {
return ResponseEntity.status(404)
.body(new ErrorResponse(404, ex.getMessage()));
}
}
public record ErrorResponse(int status, String message) {}
30. What is Spring Actuator?
Ready-to-use monitoring endpoints:
# application.yml
management:
endpoints:
web:
exposure:
include: health, info, metrics
| Endpoint | What it shows |
|---|---|
/actuator/health | App is UP or DOWN |
/actuator/info | App information |
/actuator/metrics | Metrics (memory, CPU, requests) |
/actuator/env | Environment variables |
Summary — The 30 concepts in 1 sentence
| Concept | In 1 sentence |
|---|---|
| DTO | Object to transport data without exposing the entity |
| MVC | Model (data), View (display), Controller (requests) |
| REST API | Web interface using GET/POST/PUT/DELETE on URLs |
| CRUD | Create, Read, Update, Delete |
| POJO | Simple Java object without framework dependency |
| Bean | Object created and managed by Spring |
| IoC | Spring creates dependencies instead of the code |
| ORM/JPA | Map Java objects to SQL tables |
| Maven | Dependency and build management |
| Tomcat | Web server embedded in Spring Boot |
| JSON | Lightweight data format (key-value) |
| Postman | Client to test APIs |
| Swagger | Automatic API documentation |
| Docker | Isolated container for the application |
| CI/CD | Automatic build + test + deployment |
| Git | Source code versioning |
| Layers | Controller → Service → Repository → DB |
| @Autowired | Automatic dependency injection |
| Record | Auto-generated immutable class (Java 16+) |
| Lombok | Automatically generates getters/setters/equals |
| ResponseEntity | Complete HTTP response (status + body) |
| @Valid | Triggers input validation |
| application.yml | Spring Boot configuration file |
| Spring Security | Authentication + authorization |
| JWT | Token to identify the user |
| CORS | Allow cross-origin requests |
| Singleton | One instance of the bean in the entire app |
| PUT vs PATCH | PUT replaces everything, PATCH modifies partially |
| Custom Exception | Custom exception with HTTP code |
| Actuator | Application monitoring and metrics |