89 Spring Boot, Security & JPA Interview Questions and Answers for Java Backend Developers
This post answers 89 interview questions Java backend developers actually get asked about Spring Boot, Spring Security, and JPA/Hibernate — with a simple explanation first and a short worked example for each one. It is Part 2 of the Java Backend Interview Question Bank series, covering sections 3–5 of the bank: Spring Framework, Spring Boot and REST APIs (Q87–136), Spring Security and authentication (Q137–151), and Hibernate, JPA and persistence (Q152–175). Part 1, 95 Microservices, Kafka & Redis Interview Questions and Answers, covered sections 7–9 (Q230–324). The rest of the bank — Core Java, SQL & Database Engineering, system design, cloud, and more — follows in the same format.
How to use it. Each section is split by priority, exactly as the bank ranks them. Very High Priority questions are the ones to master first — they are the fundamentals interviewers return to again and again. High Priority questions cover practical implementation, troubleshooting, and trade-offs. Medium Priority questions add breadth for senior or company-specific rounds. If you are short on time, do the Very High questions in all three sections first; that is 39 questions and the core of the topic. If you want the Spring Boot fundamentals in a shorter form first, the site's earlier Spring Boot Interview Questions and Answers (2026 Edition) covers the same ground in less depth.
A note on the examples: they are short and standard — a few lines of Java, a config snippet, or a concrete scenario — and they are meant to show the shape of an answer, not to be copied into production as-is. Where an example would be contrived, the answer says so and gives the rule instead. Nothing here was compiled or run; the code is written to be read and reasoned about, the way you would reason about it in an interview.
3. Spring Framework, Spring Boot & REST APIs
Very High Priority
87. What is IoC, and how does Dependency Injection work inside the Spring container?
Inversion of Control (IoC) means your classes do not create the objects they depend on — something else does. Instead of a service calling new UserRepository(), the Spring container creates the repository and hands it to the service. Dependency Injection (DI) is the way IoC is done in practice: the container reads the application's configuration (annotations such as @Component and @Autowired, or @Bean methods), builds a graph of beans, resolves each bean's dependencies, and injects them — usually through the constructor. The benefit is loose coupling: a class depends on an interface, not on a concrete construction, so you can swap implementations and test with mocks without changing the class. The container also owns the beans' lifecycle, creating them at startup and destroying them at shutdown.
Example:
@Service
public class OrderService {
private final OrderRepository repository;
public OrderService(OrderRepository repository) { // container injects it
this.repository = repository;
}
}88. What is the difference between constructor, setter and field injection? Why is constructor injection usually preferred?
Constructor injection passes dependencies through the constructor, setter injection through setter methods, and field injection by annotating a field directly with @Autowired. Constructor injection is preferred for three reasons. First, dependencies are explicit and mandatory: the object cannot be created without them, so a missing bean fails fast at startup instead of later with a NullPointerException. Second, fields can be final, so the object is immutable after construction. Third, testing is easy — you just call new OrderService(mockRepo) with no reflection or Spring context. Setter injection suits optional dependencies that can change after construction, but it leaves the object in a half-built state until the setter is called. Field injection is the weakest option: dependencies are hidden, the class cannot be used outside Spring without reflection, and it is hard to test. As a rule of thumb, use constructor injection by default and reach for setters only for genuinely optional, reconfigurable dependencies.
Example: new OrderService(orderRepository) in a unit test works with constructor injection and needs no Spring at all; with field injection the same test needs reflection or a Spring test context to set the private field.
89. What is the difference between @Component, @Service and @Repository?
All three are stereotype annotations that mark a class as a Spring bean discovered by component scanning, and functionally they behave the same at the container level. The difference is meaning — and one technical extra. @Component is the generic marker for any Spring-managed class. @Service marks a class in the service layer, where business logic lives; it signals intent to readers and to tools. @Repository marks a data-access class, and it carries one real behavior: Spring's exception translation, which converts database-specific exceptions such as SQLException into Spring's consistent DataAccessException hierarchy. Use the most specific annotation for the layer you are in: @Service for business logic, @Repository for data access, @Component for anything else, such as a utility or helper bean.
Example:
@Repository
public class JdbcOrderRepository { /* SQLExceptions become DataAccessExceptions */ }
@Service
public class OrderService { /* business rules, calls the repository */ }90. What is the difference between @Bean and @Component?
@Component is a class-level annotation: you put it on your own class and component scanning picks it up and registers it as a bean. @Bean is a method-level annotation used inside a @Configuration class: the method's return value becomes a bean, and you control exactly how it is built. Use @Component (and its specializations) for classes you own and can annotate. Use @Bean when you cannot annotate the class — for example a third-party class such as a RestTemplate, a DataSource, or an ObjectMapper — or when construction needs custom logic, such as reading configuration and choosing an implementation. @Bean methods can also take parameters, and Spring injects those parameters as dependencies.
Example:
@Configuration
public class AppConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplateBuilder()
.setConnectTimeout(Duration.ofSeconds(2))
.build();
}
}91. What happens internally when @SpringBootApplication is used?
@SpringBootApplication is a convenience meta-annotation that combines three annotations. @SpringBootConfiguration marks the class as a configuration source, so its @Bean methods are registered. @EnableAutoConfiguration turns on auto-configuration, which inspects the classpath and applies sensible default beans (a DataSource when a database driver is present, a web server when Spring MVC is present, and so on). @ComponentScan scans the package of the annotated class — and its sub-packages — for @Component, @Service, @Repository, and @Controller classes and registers them as beans. When the application starts, SpringApplication.run() creates the application context, performs the scan, applies auto-configuration with its conditions, instantiates the beans, and starts the embedded server. One practical consequence: keep the main class at the root of your package tree, or beans in sibling packages will not be scanned.
Example: Placing the main class in com.shop scans com.shop.orders and com.shop.users automatically; placing it in com.shop.orders would miss the com.shop.users package entirely.
92. How does Spring Boot auto-configuration work, and how do conditional annotations affect bean creation?
Auto-configuration is Spring Boot's way of providing default beans based on what is on the classpath. Each auto-configuration class is an ordinary @Configuration class guarded by conditions, and Boot loads them from META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports (in older versions, spring.factories). The conditions decide whether the configuration applies: @ConditionalOnClass checks a class is present, @ConditionalOnMissingBean applies only if you have not defined your own bean of that type, @ConditionalOnProperty checks a configuration property, and @ConditionalOnWebApplication checks the app is a web app. This is why adding a starter "just works" — the starter brings the library, the condition matches, and the default bean appears — and why defining your own bean of the same type silently replaces the default. You can exclude specific auto-configurations with exclude on @SpringBootApplication, and the auto-configuration report (--debug or the /conditions Actuator endpoint) shows exactly which configurations matched and which did not, and why.
Example: Adding spring-boot-starter-data-jpa puts Hibernate on the classpath, so HibernateJpaAutoConfiguration matches and creates an EntityManagerFactory. Defining your own DataSource bean means the default one is skipped because of @ConditionalOnMissingBean.
93. What is the Spring Bean lifecycle?
The lifecycle is the sequence of steps the container follows from creating a bean to destroying it. First the container instantiates the bean (via its constructor) and populates its properties with injected dependencies. Then, if the bean implements aware interfaces such as BeanNameAware or ApplicationContextAware, the container calls them. Next, BeanPostProcessor methods run before initialization, then the bean's own initialization runs — @PostConstruct methods, InitializingBean.afterPropertiesSet(), or a custom init-method — and then post-processors run after initialization. The bean is now ready and stays in the container until shutdown, when destruction runs in reverse: @PreDestroy methods, DisposableBean.destroy(), or a custom destroy-method. Most application code only needs @PostConstruct for setup after injection and @PreDestroy for cleanup; the rest matters when you write infrastructure such as custom post-processors or proxies.
Example:
@Component
public class CacheWarmer {
@PostConstruct
public void warmUp() { /* runs once, after all dependencies are injected */ }
@PreDestroy
public void shutDown() { /* runs once, at application shutdown */ }
}94. What are Spring Bean scopes? What is the default scope?
A scope controls how many instances of a bean the container creates and how long each lives. The default scope is singleton: one instance per container, shared by every injection point, created at startup (unless lazy). prototype creates a fresh instance every time the bean is requested — the container does not manage its destruction, so cleanup is your job. The web scopes apply only in a web application: request creates one instance per HTTP request, session one per HTTP session, application one per ServletContext, and websocket one per WebSocket session. The common mistake is injecting a short-lived bean into a singleton: the singleton holds the first instance forever. The fix is a scoped proxy (proxyMode = ScopedProxyMode.TARGET_CLASS) or ObjectProvider, so each use resolves the current request- or session-scoped instance.
Example:
@Component
@Scope(value = WebApplicationContext.SCOPE_REQUEST,
proxyMode = ScopedProxyMode.TARGET_CLASS)
public class RequestContext { /* one instance per HTTP request */ }95. What happens internally when @Transactional is used? Explain proxy-based transaction management.
@Transactional works through a proxy. When Spring finds the annotation on a bean, it wraps the bean in a proxy — a JDK dynamic proxy if the bean implements an interface, or a CGLIB subclass otherwise. Calls that go through the proxy are intercepted: the proxy asks the transaction manager to begin a transaction, invokes the real method, and then commits on success or rolls back if a runtime exception escapes. The proxy also binds the transaction to the current thread, so a repository called inside the method joins the same transaction and uses the same database connection. Three consequences follow from this design. First, only public methods called from outside the bean are intercepted — a call from one method of the bean to another (self-invocation) bypasses the proxy and runs with no transaction. Second, the proxy can only advise methods it can override, so final or private methods are never transactional. Third, rollback by default happens only for unchecked exceptions; a checked exception commits unless you declare rollbackFor.
Example:
@Transactional
public void placeOrder(Order order) {
orderRepository.save(order); // same transaction
inventoryService.reserve(order); // same transaction; failure rolls both back
}96. What are transaction propagation and isolation levels in Spring? How do nested transactions behave?
Propagation says what happens when a transactional method is called while a transaction already exists. REQUIRED (the default) joins the existing transaction or starts a new one; REQUIRES_NEW always starts a new one, suspending the current transaction; NESTED runs inside the current transaction using a savepoint, so it can roll back independently; SUPPORTS joins if one exists and runs without one otherwise; NOT_SUPPORTED suspends any current transaction; MANDATORY requires one and fails without it; NEVER fails if one exists. Isolation says how much one transaction sees of another's uncommitted work: READ_UNCOMMITTED can see dirty reads, READ_COMMITTED (the default in most databases) sees only committed rows, REPEATABLE_READ guarantees the same rows read twice match, and SERIALIZABLE is fully isolated but slowest. Nested transactions deserve care: NESTED depends on savepoint support from the JDBC driver, and a rollback of the nested part rolls back only to the savepoint, while a rollback of the outer transaction rolls back everything including the nested work.
Example: An audit write with REQUIRES_NEW commits even if the outer order transaction rolls back — useful for audit logs, dangerous if you expected the audit to disappear with the failed order.
97. What are common reasons @Transactional may not work as expected?
Most failures come from the proxy mechanism or from rollback rules. The classic cause is self-invocation: a method in the same bean calling another @Transactional method directly bypasses the proxy, so no transaction starts. Annotating a private or final method also fails, because the proxy cannot intercept it. A second group is exception handling: by default Spring rolls back only on unchecked exceptions, so a checked exception (or an exception that is caught and swallowed inside the method) commits the transaction. A third group is configuration: the annotation is on a class that is not a Spring bean, the transaction manager is misconfigured, or the method is called before the proxy is in place. Finally, propagation surprises: REQUIRES_NEW commits independently of the outer transaction, and a method that starts its own transaction can commit work you expected to roll back with the caller. When debugging, enable transaction logging and check whether a transaction is actually active at the point you expect it.
Example:
// BROKEN: self-invocation bypasses the proxy — save() runs without a transaction
public void placeOrder(Order o) { save(o); }
@Transactional
public void save(Order o) { orderRepository.save(o); }
// FIXED: call through the injected proxy, or move save() to another bean 98. How do you implement global exception handling using @ControllerAdvice and @ExceptionHandler?
@ControllerAdvice marks a class whose @ExceptionHandler methods apply to exceptions thrown by any controller, so error handling lives in one place instead of being repeated in every endpoint. Each handler method takes the exception type it handles and returns a response — usually a ResponseEntity carrying a consistent error body with a message, an error code, and a timestamp — and you annotate it with the HTTP status the error should produce. You can also handle validation errors (MethodArgumentNotValidException) the same way, and use @ResponseStatus on custom exception classes for simple cases. The result is that controllers stay focused on the happy path, clients always receive errors in the same shape, and the status codes are chosen deliberately rather than defaulting to 500 for everything.
Example:
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(OrderNotFoundException.class)
public ResponseEntity<ErrorResponse> handleNotFound(OrderNotFoundException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(new ErrorResponse("ORDER_NOT_FOUND", ex.getMessage()));
}
}99. How do you validate incoming request data using Bean Validation and custom annotations?
Bean Validation (Jakarta Validation, formerly javax.validation) lets you declare rules on your request objects with annotations and have them checked automatically. Annotate the controller parameter with @Valid (or @Validated for groups), and put constraints on the DTO fields: @NotNull, @NotBlank, @Size, @Min/@Max, @Email, @Pattern. If validation fails, Spring throws MethodArgumentNotValidException, which your global exception handler turns into a 400 response listing the field errors. For rules the built-in annotations cannot express — such as "start date must be before end date" — you write a custom constraint: an annotation plus a ConstraintValidator implementation, which keeps the rule reusable and testable. Validation belongs at the boundary: validate incoming DTOs on entry, and keep business-rule validation in the service layer, where it has access to the database.
Example:
public record CreateOrderRequest(
@NotNull Long customerId,
@NotEmpty List<@NotNull Long> productIds,
@Positive int quantity) {}
@PostMapping("/orders")
public Order create(@Valid @RequestBody CreateOrderRequest request) { ... }100. What is the difference between @Controller and @RestController?
@RestController is @Controller plus @ResponseBody on every method. A @Controller method's return value is interpreted as a view name: Spring resolves it to a template (Thymeleaf, JSP) and renders HTML. A @RestController method's return value is written directly to the HTTP response body, serialized to JSON (or XML) by an HttpMessageConverter. For a REST API you use @RestController on the class; you would only use plain @Controller when serving server-rendered pages, or add @ResponseBody to individual methods in a mixed controller. A common beginner mistake is returning an object from a @Controller without @ResponseBody and getting a "view not found" error, because Spring tried to resolve the object's class name as a template.
Example:
@RestController
@RequestMapping("/api/orders")
public class OrderController {
@GetMapping("/{id}")
public Order get(@PathVariable Long id) { return orderService.find(id); }
// returned Order is serialized to JSON automatically
}101. What is the difference between @PathVariable, @RequestParam and @RequestBody?
All three bind parts of an HTTP request to method parameters, but to different parts. @PathVariable binds a segment of the URL path, used to identify a resource: /orders/{id}. @RequestParam binds a query parameter, used for optional filters and options: /orders?status=PAID&page=2. @RequestBody binds the whole request body, usually JSON, deserialized into an object — used for creating or updating a resource. A useful rule of thumb: the path identifies which resource, query parameters say how to fetch or filter it, and the body carries what to create or change. @RequestParam can be optional with required = false and a defaultValue; @PathVariable is required by default; @RequestBody is required by default and needs a matching Content-Type such as application/json.
Example:
@GetMapping("/orders/{id}") // PathVariable: which order
public Order get(@PathVariable Long id,
@RequestParam(defaultValue = "false") boolean includeItems) { ... }
@PostMapping("/orders") // RequestBody: what to create
public Order create(@Valid @RequestBody CreateOrderRequest body) { ... }102. What is the difference between POST, PUT and PATCH? Explain HTTP idempotency.
An operation is idempotent when repeating it has the same effect as doing it once. POST creates a new resource under a collection (POST /orders) and is not idempotent — repeating it creates a second order, which is why payment endpoints need idempotency keys. PUT replaces a resource at a known URI (PUT /orders/42) with the full representation, and is idempotent — sending the same full object ten times leaves the same state. PATCH applies a partial update (PATCH /orders/42 with only the changed fields); it is idempotent only if the patch semantics make it so, for example setting a field to a fixed value, whereas an instruction such as "increment quantity by 1" is not idempotent. In an interview the key points are: POST for create, PUT for full replace, PATCH for partial update, and the idempotency of each — plus the practical consequence that clients may safely retry PUT but must not blindly retry POST.
Example: A client whose POST /payments request times out cannot know whether the payment went through, so it retries with the same idempotency key; a PUT /users/7 retry is safe by definition because it writes the same full user object again.
103. What are REST API design best practices, including status codes and resource naming?
Good REST design starts with resources as nouns, not verbs: /orders and /orders/{id}/items, never /getOrders or /createOrder. Use the HTTP method for the action (GET read, POST create, PUT replace, PATCH partial update, DELETE remove) and nest resources only one level deep where the child cannot exist without the parent. Status codes should be precise: 200 for a successful read, 201 for a created resource (with a Location header), 204 for a successful delete with no body, 400 for invalid input, 401 for unauthenticated, 403 for forbidden, 404 for a missing resource, 409 for a conflict such as a duplicate, and 500 only for genuine server errors. Errors should share one consistent body shape with a machine-readable code and a human-readable message. Finally, paginate list endpoints, version the API before it is public, and keep responses stable — adding a field is safe, renaming or removing one is a breaking change.
Example: GET /orders?page=0&size=20&status=PAID returns 200 with a page of orders; POST /orders with a missing customer returns 400 with {"code": "VALIDATION_FAILED", "message": "customerId is required"}.
104. How do you implement pagination and sorting using Spring Data JPA?
Spring Data JPA implements pagination through the Pageable interface. A repository method that takes a Pageable and returns a Page<T> runs two queries: one for the requested slice of rows and one count query for the total, so the client can compute the number of pages. You build the Pageable with PageRequest.of(page, size, Sort.by("createdAt").descending()) — note that page numbers are zero-based, so the first page is 0. Sort can chain several fields, and Sort.by(Sort.Direction.DESC, "total", "id") gives a deterministic order even when the first field ties. For very large tables, offset pagination gets slower as the page number grows, because the database still scans the skipped rows; keyset pagination (filtering on the last seen id) is the faster alternative, but offset pagination is the standard answer and is fine for most admin and listing screens.
Example:
Page<Order> page = orderRepository.findByStatus(
OrderStatus.PAID,
PageRequest.of(0, 20, Sort.by("createdAt").descending()));
// page.getContent() — the 20 orders; page.getTotalElements() — the full count105. What is the difference between RestTemplate and WebClient?
RestTemplate is Spring's original HTTP client: synchronous and blocking — the calling thread waits for the response — with a simple template API. WebClient is its reactive successor: non-blocking, built on Reactor, returning Mono or Flux, and able to stream responses and handle many concurrent calls on few threads. Spring's own guidance is that RestTemplate is in maintenance mode and new code should use WebClient, but RestTemplate is not removed and remains fine for simple synchronous calls, such as a service-to-service call inside a blocking application. The choice follows the application's model: a reactive or high-concurrency service benefits from WebClient; a straightforward blocking service can keep RestTemplate without harm. One practical difference: testing differs, since WebClient calls return publishers that must be subscribed to or blocked on in tests.
Example:
// Blocking, simple
Order order = restTemplate.getForObject("http://order-service/orders/{id}", Order.class, id);
// Non-blocking, composable
Mono<Order> order = webClient.get().uri("/orders/{id}", id)
.retrieve().bodyToMono(Order.class);106. How do you secure REST APIs in Spring Boot?
Securing a REST API is a stack of layers, not a single feature. Transport comes first: serve everything over HTTPS so tokens and data cannot be sniffed. Authentication identifies the caller — usually a JWT bearer token or OAuth2, validated on every request by a security filter (the details are in section 4). Authorization then decides what the authenticated caller may do, using roles or authorities on endpoints and methods. Input validation rejects malformed data before it reaches business logic, and output should never leak sensitive fields — use DTOs rather than exposing entities directly. Rate limiting and request-size limits blunt abuse, CORS must be configured deliberately rather than opened to *, and error responses must not leak internals such as stack traces. Finally, secrets belong in a vault or environment variables, never in code or in responses, and dependencies should be kept patched.
Example: A rule instead of a contrived code sample: an endpoint that accepts a JWT, checks the caller has the ORDER_READ authority, validates the input DTO, returns a DTO with no internal ids or password hashes, and sits behind HTTPS and a rate limit is secured; any one missing layer is a gap, not a detail.
High Priority
107. What is the difference between Spring and Spring Boot?
Spring Framework is the foundation: dependency injection, the application context, Spring MVC, transaction management, and data access. It is powerful but requires explicit configuration — you declare beans, set up a DispatcherServlet, and choose versions of every dependency yourself. Spring Boot is an opinionated layer on top of Spring that removes that boilerplate: starters bundle compatible dependencies, auto-configuration provides sensible default beans, an embedded server (Tomcat, Jetty, or Undertow) means the application runs as a plain java -jar, and Actuator adds production endpoints. Boot does not replace Spring — a Boot application is a Spring application, and anything you can do in Spring you can do in Boot by overriding the defaults. The interview line is simple: Spring gives you the pieces, Boot gives you a working application from those pieces with minimal configuration.
Example: A plain Spring MVC application needs a web.xml or initializer, a servlet container installation, and manual dependency versions; the same application in Boot needs a starter dependency and a main class with @SpringBootApplication, and it runs with java -jar app.jar.
108. What is the difference between @Autowired, @Qualifier and @Primary?
@Autowired tells Spring to inject a dependency by type. When exactly one bean of that type exists, that is all you need. When several beans of the same type exist, injection becomes ambiguous and Spring fails at startup — that is where the other two come in. @Qualifier names the specific bean to inject, and you put it at the injection point, next to @Autowired or on the constructor parameter. @Primary marks one bean definition as the default, so it wins whenever no qualifier is given. Use @Primary for the normal implementation and @Qualifier at the places that need the special one; using qualifiers everywhere is explicit but noisy, and relying on @Primary everywhere hides which implementation is actually wired.
Example:
@Service @Primary
public class EmailNotifier implements Notifier { ... }
@Service("smsNotifier")
public class SmsNotifier implements Notifier { ... }
// Injects EmailNotifier by default; use @Qualifier("smsNotifier") for the SMS one
public AlertService(Notifier notifier) { ... }109. What is the difference between application.properties and application.yml?
Both are Spring Boot's external configuration files and they configure exactly the same properties; only the format differs. application.properties is flat key=value lines, one property per line. application.yml is YAML: hierarchical indentation, so related properties nest under a common key, and lists and maps are natural to express. YAML is usually easier to read for nested configuration such as security rules or server settings, while properties is simpler and less error-prone — a single wrong space in YAML silently changes the structure, which is the most common YAML bug. Boot loads application.properties first if both exist, so do not keep both with overlapping keys. The choice is a team preference; what matters is consistency and keeping secrets out of either file — use environment variables or a secret store for those.
Example:
# application.properties
server.port=8081
spring.datasource.url=jdbc:mysql://localhost:3306/shop
# application.yml — the same two settings
server:
port: 8081
spring:
datasource:
url: jdbc:mysql://localhost:3306/shop110. What are Spring Profiles, and how do you manage configuration for different environments?
Profiles let you activate different beans and configuration per environment — dev, test, prod — without changing code. You mark a bean or configuration class with @Profile("prod") so it is created only when that profile is active, and you set the active profile with spring.profiles.active (property, environment variable, or command-line argument). Configuration files follow the same pattern: application-prod.properties overrides application.properties only when prod is active. The discipline that matters is keeping environment differences in configuration, not in code: database URLs, feature flags, and log levels come from properties; code stays the same across environments. Secrets must not live in profile files — they come from environment variables or a vault, since profile files are usually committed to source control.
Example:
@Configuration
@Profile("dev")
public class DevConfig {
@Bean
public MailSender mailSender() { return new LoggingMailSender(); } // logs instead of sending
}111. What is @ConfigurationProperties, and how does it differ from @Value?
@ConfigurationProperties binds a whole group of related properties to a typed POJO, with a prefix, relaxed binding (so app.cache.ttl-seconds maps to ttlSeconds), and optional JSR-303 validation with @Validated. @Value injects a single property value into one field, using a placeholder such as ${app.name} or a SpEL expression. The practical difference is scale: one or two values — use @Value; a coherent group such as all mail settings or all cache settings — use @ConfigurationProperties, because the class documents the group, is type-safe, is easy to test, and fails clearly at startup when a required value is missing or mistyped. @Value fails later and more quietly, and scattering it across classes makes configuration hard to audit.
Example:
@ConfigurationProperties(prefix = "app.cache")
@Validated
public record CacheProperties(@NotNull Duration ttl, @Min(1) int maxEntries) {}
// @Value equivalent for a single value:
@Value("${app.name}") private String appName;112. What is @ConditionalOnProperty, and when would you use it?
@ConditionalOnProperty creates a bean only when a configuration property has a particular value — or is present or absent. Its main use is feature flags and optional integrations: a bean that should exist only when a feature is switched on, or a fallback bean that should exist only when a property is not set. You give it the property name, and optionally havingValue and matchIfMissing. It is the same mechanism auto-configuration uses internally, and it keeps feature toggles declarative: flipping a property in configuration changes the wiring without a code change or redeploy of a different build. One caution: a misspelled property name silently disables the bean, so pair it with a startup log line or a configuration-properties class that validates the property exists.
Example:
@Bean
@ConditionalOnProperty(name = "app.features.recommendations", havingValue = "true")
public RecommendationService recommendationService() { ... }
// Bean exists only when app.features.recommendations=true in configuration113. What is lazy initialization, and how can it be enabled?
By default Spring creates all singleton beans at startup (eager initialization), so a misconfigured bean fails fast before the application serves traffic. Lazy initialization defers bean creation until the bean is first used. You enable it per bean with @Lazy, or for the whole application with spring.main.lazy-initialization=true. The benefit is a faster startup, which matters for large applications and for serverless or CLI tools; the cost is that configuration errors surface later — the first request that touches the bean fails instead of the application failing at boot — and the first request pays the initialization cost. As a rule of thumb, keep eager initialization for services and use @Lazy selectively for expensive beans that are rarely needed, such as a heavy report generator, rather than lazily initializing everything.
Example: A rarely used PDF-report bean marked @Lazy is not created at startup, so the application starts in 3 seconds instead of 8; the first report request takes slightly longer while the bean is built.
114. What is Spring AOP, and how does proxy-based AOP work?
Aspect-Oriented Programming (AOP) separates cross-cutting concerns — behavior needed in many places, such as logging, security checks, or transactions — from business logic. You write the concern once as an aspect, with advice (the code to run) and a pointcut (an expression saying where it applies: which methods, which classes). Spring AOP is proxy-based: for each bean matching a pointcut, Spring creates a proxy around it, and the proxy runs the advice before, after, or around the target method. For beans implementing interfaces it uses JDK dynamic proxies; otherwise it uses CGLIB subclasses. The same limits as @Transactional apply, because transactions are themselves built on AOP: advice runs only on public methods called through the proxy, so self-invocation and final methods escape it. Use AOP for infrastructure concerns, not for core business rules — business logic hidden in aspects is hard to discover and debug.
Example:
@Aspect
@Component
public class LoggingAspect {
@Around("execution(* com.shop.orders.*.*(..))")
public Object logTime(ProceedingJoinPoint pjp) throws Throwable {
long start = System.currentTimeMillis();
Object result = pjp.proceed(); // call the real method
log.info("{} took {} ms", pjp.getSignature(), System.currentTimeMillis() - start);
return result;
}
}115. What is the difference between @RequestMapping and its shortcut annotations?
@RequestMapping is the general mapping annotation: you specify the path and, with the method attribute, the HTTP method. The shortcut annotations — @GetMapping, @PostMapping, @PutMapping, @DeleteMapping, @PatchMapping — are composed annotations built on @RequestMapping with the method already fixed. They exist for readability: @GetMapping("/orders") says in one word what @RequestMapping(value = "/orders", method = RequestMethod.GET) says in many. Use the shortcuts in normal controllers and keep @RequestMapping for the class-level base path and for the rare case where one method handles several HTTP methods.
Example:
@RestController
@RequestMapping("/api/orders") // base path for the whole controller
public class OrderController {
@GetMapping("/{id}") // GET /api/orders/{id}
public Order get(@PathVariable Long id) { ... }
@PostMapping // POST /api/orders
public Order create(@RequestBody CreateOrderRequest body) { ... }
}116. What is the difference between @ResponseBody and @RequestBody?
Both deal with the HTTP message body, in opposite directions. @RequestBody goes on a method parameter: Spring reads the request body (usually JSON) and deserializes it into the parameter's type using an HttpMessageConverter. @ResponseBody goes on a method or class: Spring serializes the return value into the response body instead of treating it as a view name. In a @RestController you rarely write @ResponseBody yourself, because the annotation already includes it; you write @RequestBody on every endpoint that accepts a JSON payload. A common error is forgetting @RequestBody and getting a null or empty object — Spring then tries to bind the JSON fields as query parameters instead.
Example:
@PostMapping("/orders")
public Order create(@RequestBody CreateOrderRequest body) { // JSON in -> object
return orderService.create(body); // object out -> JSON
}117. How do you change the default server port in Spring Boot?
The default embedded Tomcat port is 8080, and the standard way to change it is the server.port property — in application.properties (server.port=8081) or application.yml (server: port: 8081). It can also be overridden at runtime without touching a file: as a command-line argument (--server.port=8081) or an environment variable (SERVER_PORT=8081). The precedence follows Spring's normal property order, so a command-line argument beats the file, which is how deployments usually set the port. Setting it to 0 picks a random free port, which is useful for tests that start a real server. A related setting is server.address, which controls which network interface the server binds to.
Example: java -jar shop.jar --server.port=8081 runs the same artifact on port 8081 with no code or file change.
118. What is Spring Boot Actuator, and how do you secure its endpoints?
Actuator exposes operational endpoints about a running application: /actuator/health for liveness and readiness, /actuator/info for build information, /actuator/metrics for counters and timers, and others such as env, loggers, and httpexchanges. Only health is exposed over HTTP by default; you enable more with management.endpoints.web.exposure.include, ideally listing endpoints explicitly rather than using *. Securing them matters because several endpoints expose internals: the standard approach is to treat Actuator as part of the application and protect it with Spring Security, for example allowing /actuator/health to everyone (load balancers need it) while requiring an admin role for the rest, and ideally restricting access by network as well. Never expose env, heapdump, or shutdown to the public internet.
Example:
management:
endpoints:
web:
exposure:
include: health, info, metrics # explicit list, never "*" in production119. What are liveness and readiness health indicators?
Health indicators tell an orchestrator whether an application is alive and whether it can serve traffic, and the two questions have different answers. Liveness asks "is the process alive?" — if liveness fails, Kubernetes restarts the container, because the application is assumed to be deadlocked or otherwise unrecoverable. Readiness asks "is the application ready to take traffic?" — if readiness fails, Kubernetes removes the pod from the load balancer but does not restart it, because the application may recover (for example, while it is still warming a cache or waiting for the database). Spring Boot Actuator separates them: /actuator/health/liveness and /actuator/health/readiness, backed by the LivenessStateHealthIndicator and ReadinessStateHealthIndicator. The classic mistake is making liveness depend on a database: a brief database outage then restarts every pod at once, turning a transient problem into a full outage. Keep liveness cheap and local; readiness may check dependencies.
Example: During startup, readiness is DOWN (traffic stays away) while liveness is UP (no restart); if the database becomes unreachable, readiness goes DOWN so the pod stops receiving requests, but liveness stays UP so Kubernetes does not restart a healthy process.
120. What is the purpose and risk of sensitive Actuator endpoints such as shutdown?
Some Actuator endpoints are powerful by design. /actuator/shutdown gracefully stops the application, /actuator/env shows configuration properties (which can include secrets), /actuator/heapdump downloads a heap dump that may contain tokens and passwords, and /actuator/loggers can change log levels at runtime. Their purpose is operations and debugging, but exposed to the wrong caller they are an attacker toolkit: shutdown is a one-request denial of service, env is a secret leak, and a heap dump is a credential harvest. The rules are simple: do not expose them at all unless a specific operational need exists, enable shutdown only deliberately (it is disabled by default), require authentication and an admin role for any exposed sensitive endpoint, and restrict access by network so only internal tooling can reach them.
Example: A rule instead of a contrived code sample: if your monitoring only needs health and metrics, expose exactly those two; every additional endpoint you expose is a new thing to secure, audit, and explain in a security review.
121. What is Spring Boot DevTools?
DevTools is a development-only module that makes the edit-run cycle faster. It watches the classpath and automatically restarts the application (using two classloaders, so only your code reloads) when you recompile, disables template caching so changes appear immediately, enables LiveReload in the browser, and applies development-friendly defaults. It is automatically disabled when the application runs from a packaged jar, so it never affects production — but you should still exclude it from production builds rather than relying on that. Its main value is for local development of web applications and APIs, where a manual restart after every change wastes minutes a day. One caveat: automatic restart can surprise you if your application holds state in memory, since a restart wipes it.
Example: With DevTools on the classpath, changing a controller method and recompiling restarts the application in a second or two, and the next request in the browser hits the new code without a manual restart.
122. What is the difference between CrudRepository and JpaRepository?
JpaRepository extends PagingAndSortingRepository, which extends CrudRepository — each layer adds operations. CrudRepository provides the basics: save, findById, findAll, deleteById, and count. PagingAndSortingRepository adds findAll(Pageable) and findAll(Sort). JpaRepository adds JPA-specific operations: saveAndFlush, deleteAllInBatch, getReferenceById, and flushing. In practice most Spring Boot applications use JpaRepository directly, since pagination and batch operations are needed sooner or later, and the extra methods cost nothing. Use CrudRepository only when you deliberately want the smallest interface — for example, to keep a repository's surface minimal in a strict layered design.
Example:
public interface OrderRepository extends JpaRepository<Order, Long> {
Page<Order> findByStatus(OrderStatus status, Pageable pageable);
}123. How do you write custom queries in Spring Data JPA?
There are three main ways, in order of preference. First, derived query methods: Spring Data parses the method name into a query, so findByEmailAndStatus(String email, OrderStatus status) needs no query text at all, and long names are a sign you should switch to the next option. Second, @Query: you write the JPQL (or native SQL with nativeQuery = true) yourself, with named parameters such as :status, which is the right choice for joins, aggregations, and anything the method-name parser cannot express. Third, for dynamic queries built at runtime, use the Specification API or QueryDSL, which compose predicates programmatically instead of concatenating query strings. As a rule of thumb, derived methods for simple lookups, @Query for anything with a join or an aggregation, and Specifications when the filters are chosen by the caller.
Example:
@Query("SELECT o FROM Order o WHERE o.customer.id = :customerId AND o.status = :status")
List<Order> findCustomerOrders(@Param("customerId") Long customerId,
@Param("status") OrderStatus status);124. How do you configure request rate limiting in a Spring Boot API?
Rate limiting caps how many requests a caller may make in a time window, protecting the service from accidental overload and abusive clients. There is no built-in Spring Boot rate limiter, so teams use a library or the gateway. Common options are Bucket4j (a token-bucket implementation that works in-process or backed by Redis for distributed limits), Resilience4j's RateLimiter, or rate limiting at the API gateway, which is the best place when several services share one limit policy. The limit is usually keyed by something meaningful — an API key, a user id, or an IP address — and enforced per endpoint or per caller. When the limit is exceeded, the API should return 429 Too Many Requests with a Retry-After header, not a 500. A token bucket is the usual algorithm: tokens refill at a steady rate, each request spends one, and requests are rejected when the bucket is empty, which allows short bursts while capping the average rate.
Example: A rule instead of a contrived code sample: limit the public login endpoint to a small number of attempts per minute per IP (which also slows brute-force attacks) and the general API to a generous per-key quota, and return 429 with Retry-After when either is exceeded.
125. How do you implement caching using Spring Cache annotations?
Spring's cache abstraction lets you add caching with annotations instead of writing cache code by hand. Enable it with @EnableCaching, then annotate methods: @Cacheable("products") runs the method on a cache miss and stores the result, returning the cached value on a hit; @CachePut always runs the method and updates the cache; @CacheEvict removes entries, typically after a write; @CacheConfig sets shared defaults such as the cache name for a class. The actual store is pluggable — Caffeine for in-process caching, Redis for a shared cache — configured through a CacheManager bean, with Boot auto-configuring one from the classpath. Two details matter: the cache key defaults to the method arguments, so customize it with SpEL (key = "#id") when the default is wrong, and remember the same proxy rules as @Transactional — self-invocation bypasses the caching proxy.
Example:
@Cacheable(value = "products", key = "#id")
public Product findProduct(Long id) { return productRepository.findById(id).orElseThrow(); }
@CacheEvict(value = "products", key = "#product.id")
public Product updateProduct(Product product) { ... }126. What is connection pooling, and why does Spring Boot commonly use HikariCP?
Opening a new database connection per request is expensive — TCP handshake, authentication, session setup — so applications keep a pool of open connections and reuse them. A connection pool hands out an idle connection when a request needs one and returns it when the request finishes, bounding the number of concurrent connections and avoiding the setup cost. Spring Boot uses HikariCP as the default pool because it is fast and has very low overhead: it is deliberately small, avoids synchronization where possible, and fails fast when the pool is exhausted instead of queuing forever. The settings that matter are the maximum pool size (too small starves requests, too large overwhelms the database — a common rule of thumb is roughly the number of CPU cores times two plus one for the database's own capacity, tuned by measurement), the connection timeout, and the idle timeout. Size the pool from the database's limits and measured load, not from a guess.
Example:
spring:
datasource:
hikari:
maximum-pool-size: 20
connection-timeout: 30000 # ms to wait for a connection before failing
minimum-idle: 5127. What is the difference between @SpringBootTest and @WebMvcTest?
@SpringBootTest loads the full application context — all beans, configuration, and infrastructure — and is used for integration tests that exercise the real wiring, usually with a test database. @WebMvcTest is a test slice: it loads only the web layer (controllers, filters, advice, and converters) and leaves services and repositories out, so you provide them as @MockBeans. The trade-off is speed versus realism: @WebMvcTest starts in a fraction of the time and is ideal for testing controller behavior, validation, status codes, and JSON shape; @SpringBootTest is slower but proves the whole application works together. A healthy test suite uses both: many fast slice tests for controllers and repositories, and a smaller number of full-context tests for end-to-end flows.
Example:
@WebMvcTest(OrderController.class)
class OrderControllerTest {
@Autowired MockMvc mockMvc;
@MockBean OrderService orderService; // web layer only; service is mocked
@Test
void getOrderReturns200() throws Exception {
when(orderService.find(1L)).thenReturn(new Order(1L));
mockMvc.perform(get("/api/orders/1")).andExpect(status().isOk());
}
}128. How do you write unit and integration tests for Spring Boot applications?
Unit tests verify one class in isolation, with its collaborators replaced by Mockito mocks: fast, numerous, and the place to test business rules. Integration tests verify several real components working together — a controller with a service and a repository against a real database — using @SpringBootTest or a slice such as @DataJpaTest for repositories. For a real database in tests, Testcontainers starts a throwaway database in Docker, which catches the SQL and dialect issues an in-memory database hides. The usual shape is a pyramid: many unit tests, fewer integration tests, and a small number of end-to-end tests. Keep tests independent and repeatable: each test sets up its own data, transactions roll back after repository tests, and no test depends on another test's execution order.
Example:
@DataJpaTest
class OrderRepositoryTest {
@Autowired OrderRepository repository;
@Autowired TestEntityManager entityManager;
@Test
void findByStatusReturnsOnlyPaid() {
entityManager.persist(new Order(OrderStatus.PAID));
entityManager.persist(new Order(OrderStatus.NEW));
assertThat(repository.findByStatus(OrderStatus.PAID)).hasSize(1);
}
}Medium Priority
129. What does @EnableAutoConfiguration do?
@EnableAutoConfiguration switches on Spring Boot's auto-configuration: Boot scans the auto-configuration classes on the classpath and applies the ones whose conditions match, creating default beans for the web layer, data access, messaging, and more. It is one of the three annotations combined by @SpringBootApplication, so you rarely write it yourself. Its main practical use is the exclude attribute: when an auto-configuration gets in your way — for example, Boot configures a DataSource you do not want — you exclude that class explicitly. The auto-configuration report shows what was applied and what was skipped, which is the first place to look when a bean you expect is missing.
Example:
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
public class ShopApplication { ... }130. What is the difference between @SpringBootConfiguration and @ComponentScan?
Both are part of @SpringBootApplication and both relate to configuration, but they do different jobs. @SpringBootConfiguration marks a class as a source of bean definitions — it is @Configuration with an extra marker that tells Boot "this is the application's primary configuration class," so Boot registers its @Bean methods and applies extra processing such as test slice configuration. @ComponentScan tells Spring which packages to scan for annotated classes (@Component, @Service, and so on) and register them as beans. In short: @SpringBootConfiguration says "this class defines beans," @ComponentScan says "go find beans in these packages." You customize the scan with scanBasePackages on @SpringBootApplication when your code lives outside the main class's package tree.
Example: A main class in com.shop with @SpringBootApplication(scanBasePackages = {"com.shop", "com.shared"}) picks up beans from a shared library package that the default scan would miss.
131. What is the /httpexchanges Actuator endpoint used for?
The /actuator/httpexchanges endpoint shows recent HTTP request-response exchanges handled by the application: the request URI, method, status, timing, and principal, in the order they arrived. It is the successor to the older /httptrace endpoint, which was removed. Its main use is debugging production issues: when a client reports a failing call, the endpoint shows what the server actually saw, including requests that never reached a controller. It records only a bounded number of exchanges (by default the last 100) and only when an HttpExchangeRepository bean is present — Boot provides an in-memory one automatically when the endpoint is exposed. Because exchanges can contain sensitive headers and bodies, keep the endpoint secured and do not expose it publicly.
Example: After a client reports intermittent 400 errors, /actuator/httpexchanges shows the failing requests with their exact URIs and statuses, revealing that the client was calling /orders without the required customerId parameter.
132. How do you configure and expose custom Actuator endpoints?
You define a custom endpoint with @Endpoint(id = "orders") on a class, adding @ReadOperation methods for reads and @WriteOperation methods for actions that change state, with parameters bound by @Selector. The endpoint appears under /actuator/orders once you include its id in management.endpoints.web.exposure.include, and it is secured like any other endpoint. Custom endpoints are the right way to expose application-specific operational information — a cache summary, a feature-flag state, or a manual trigger for a maintenance job — instead of building one-off admin controllers. Keep read operations cheap and side-effect free, and treat write operations like any other mutating API: authenticated, authorized, and audited.
Example:
@Component
@Endpoint(id = "cache")
public class CacheEndpoint {
@ReadOperation
public Map<String, Object> stats() {
return Map.of("entries", cache.estimatedSize(), "hits", cache.stats().hitCount());
}
}133. What is the difference between filters, HandlerInterceptors and AOP advice?
All three intercept requests, but at different layers. A servlet Filter runs at the servlet-container level, before the request reaches Spring's DispatcherServlet: it sees the raw request and response, which makes it the right place for authentication, request logging, and compression. A HandlerInterceptor runs inside Spring MVC, around the handler (controller) method: preHandle runs before the controller, postHandle after it returns, and afterCompletion after the response is rendered — the right place for cross-cutting web concerns such as adding model data or measuring handler time, with access to the handler itself. AOP advice runs at the method level around any Spring bean method, not just web handlers, and is the right place for concerns such as transactions and method-level security. The execution order for a web request is filter, then interceptor preHandle, then the controller method (with any AOP advice around it), then interceptor postHandle and afterCompletion, then the filter's remaining code.
Example: Authentication belongs in a filter (it must run before routing); a "current user" audit log belongs in an interceptor (it needs the handler); a retry or timing concern on a service method belongs in AOP advice.
134. What is the Spring MVC request lifecycle from DispatcherServlet to controller?
Every request enters through the DispatcherServlet, the front controller. It first asks a HandlerMapping which controller method handles the request, then runs any HandlerInterceptor preHandle methods. A HandlerAdapter then invokes the controller method, resolving its arguments — @PathVariable, @RequestParam, @RequestBody, the principal — and if the method throws, a HandlerExceptionResolver (including your @ControllerAdvice) converts the exception into a response. The controller returns either a view name with a model or, for REST, an object: for a view, a ViewResolver renders the template; for a REST response, an HttpMessageConverter serializes the object to JSON. Finally the interceptors' postHandle and afterCompletion methods run, and the response goes back to the client. Filters wrap the whole flow, since they run outside the DispatcherServlet.
Example: A rule instead of a contrived code sample: when a request returns 404, the cause is usually in the HandlerMapping step (no method matches the path); when a request returns 400, the failure is usually in argument resolution (a missing or invalid parameter) before the controller body ever runs.
135. What is CORS, why does it occur, and how do you troubleshoot it?
CORS (Cross-Origin Resource Sharing) is a browser security rule: a web page loaded from one origin (scheme, host, and port) may not call an API on a different origin unless the API explicitly allows it. The browser enforces this, not the server — a curl call to the same API works fine, which is the first clue when troubleshooting. For non-simple requests the browser first sends a preflight OPTIONS request, and the server must answer with Access-Control-Allow-Origin and the allowed methods and headers. In Spring Boot you configure CORS with @CrossOrigin on a controller or a global CorsConfigurationSource bean; with Spring Security you must wire it through http.cors() so the security filter chain applies the same rules. Troubleshooting steps: confirm the error is in the browser (not in curl), check the preflight response, verify the origin, methods, and headers are allowed, and check the credentials flag — allowCredentials(true) cannot be combined with a wildcard origin.
Example:
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(List.of("https://shop.example.com"));
config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE"));
config.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return source;
}136. What is API versioning, and when should it be introduced?
API versioning lets you change an API without breaking existing clients: old clients keep calling the old version while new clients use the new one. Common strategies are URI versioning (/api/v1/orders), header versioning (a custom header such as X-API-Version: 2), query-parameter versioning (?version=2), and content negotiation (a versioned media type). URI versioning is the most common because it is visible and easy to test, even though it is arguably the least RESTful. Introduce versioning when the API has external consumers you cannot update yourself — before the first breaking change, not after it. For internal APIs used by one team, versioning is usually overkill; evolve the API and update the callers together. When you do version, support the old version for a announced deprecation period, document what changed, and never silently change the meaning of an existing field.
Example: Adding a required field to the order response is a breaking change: ship it as /api/v2/orders while /api/v1/orders keeps serving the old shape until the announced deprecation date.
4. Spring Security & Authentication
Very High Priority
137. Explain the Spring Security filter chain and how authentication and authorization work.
Spring Security is built on a chain of servlet filters that every request passes through before reaching your controller. The chain is ordered: early filters handle concerns such as CORS, CSRF, and security headers; the authentication filters then try to identify the caller — for example, a UsernamePasswordAuthenticationFilter reads login credentials, or a JWT filter reads a bearer token — and hand the credentials to an AuthenticationManager, which delegates to an AuthenticationProvider (often a UserDetailsService backed by a database) to verify them. On success, the resulting Authentication object, carrying the principal and its granted authorities, is stored in the SecurityContext, which is held per thread (and per session, if sessions are used). Later, the authorization filter checks whether that authentication is allowed to access the requested resource, using the rules you configured — URL patterns, roles, or method-level annotations. If authentication fails, the request is rejected with 401; if authentication succeeds but authorization fails, it is rejected with 403. The key mental model is that the filters run before your code, the SecurityContext is how your code learns who the caller is, and authorization is a separate step from authentication.
The chain looks like this:
Example: A request to GET /orders/42 with a bearer token passes the CORS and header filters, the JWT filter validates the token and stores an Authentication with authority ORDER_READ in the SecurityContext, and the authorization filter allows the request because the endpoint requires ORDER_READ. The same request without a token fails at authentication with 401.
138. How do you implement JWT authentication in Spring Boot, step by step?
The flow has two parts: issuing the token at login, and validating it on every later request. First, add the Spring Security starter and a JWT library, and configure a SecurityFilterChain that is stateless (SessionCreationPolicy.STATELESS), permits the login endpoint, and requires authentication for the rest. Second, implement login: a controller receives username and password, the AuthenticationManager verifies them against a UserDetailsService and a password encoder, and on success you build a JWT — header, claims (subject, roles, issued-at, expiry), signed with a strong secret key — and return it. Third, add a filter that runs before the standard authentication filter: it reads the Authorization: Bearer <token> header, verifies the signature and expiry, extracts the user and authorities, and stores an Authentication in the SecurityContext. Fourth, protect the endpoints with authorization rules. The common mistakes are a weak or hard-coded signing key, an expiry that is far too long, and forgetting that the token is stateless — revoking it needs a denylist or short expiries with refresh tokens.
Example:
// Login: authenticate, then issue a signed token (jjwt shown; any JWT library works)
Authentication auth = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(request.username(), request.password()));
String token = Jwts.builder()
.subject(auth.getName())
.claim("roles", auth.getAuthorities().stream().map(GrantedAuthority::getAuthority).toList())
.issuedAt(new Date())
.expiration(new Date(System.currentTimeMillis() + 900_000)) // 15 minutes
.signWith(signingKey)
.compact();139. What is the difference between authentication and authorization?
Authentication answers "who are you?" and authorization answers "what are you allowed to do?" Authentication happens first: the system verifies identity, by checking a password, validating a token, or confirming a certificate, and establishes a principal. Authorization happens after: given that identity, the system checks permissions — roles, authorities, or ownership — before allowing an action. The two are often confused because they sit next to each other in a security filter chain, but they fail differently and are fixed differently: a 401 Unauthorized means authentication failed or is missing, while a 403 Forbidden means authentication succeeded but the caller lacks permission. A useful interview line is that authentication without authorization lets everyone in, and authorization without authentication has nobody to check — you need both, in that order.
Example: A user logs in with a valid password (authenticated) and tries to delete another user's order; the request is rejected with 403 because their role does not include order deletion (not authorized).
140. What is the difference between JWT and OAuth 2.0?
A JWT is a token format; OAuth 2.0 is a protocol. A JWT (JSON Web Token) is a compact, self-contained, signed token with three base64url parts — header, payload (claims), and signature — that anyone holding the signing key can verify without calling the issuer. OAuth 2.0 is a delegation framework: it defines how a client obtains an access token to act on a user's behalf, through flows such as authorization code, client credentials, and refresh token, without ever seeing the user's password. The two are usually used together: an OAuth 2.0 authorization server issues access tokens, and those tokens are often JWTs. Saying "we use JWT instead of OAuth2" is a category error — the real choice is whether you need delegation (OAuth 2.0) and, if so, which token format your authorization server issues.
Example: "Sign in with Google" is OAuth 2.0: your application never sees the user's Google password; Google issues an access token (often a JWT) that your application uses to call Google's APIs on the user's behalf.
141. How do access tokens and refresh tokens work? How should token expiry and rotation be handled?
An access token is a short-lived credential (commonly 5–15 minutes) sent with every API call; a refresh token is a longer-lived credential (hours to days) used only to obtain a new access token when the old one expires, without making the user log in again. The split limits damage: if an access token leaks, it dies within minutes, while the refresh token is stored more carefully — typically as an httpOnly cookie or in secure storage — and is sent only to the token endpoint. Rotation means each use of a refresh token issues a new refresh token and invalidates the old one; if an old refresh token is presented again, that signals theft, and the server should revoke the whole token family. Refresh tokens should be stored server-side (or at least their hashes) so they can be revoked on logout or on suspicion of compromise, and absolute expiry should bound how long a session can be refreshed without re-authentication.
Example: A mobile app holds a 15-minute access token and a 7-day refresh token. When an API call returns 401 for expiry, the app calls POST /auth/refresh with the refresh token, receives a new access token and a new refresh token, and retries — the user never sees a login screen unless the refresh token itself has expired or been revoked.
142. How do you secure communication and authenticate requests between microservices?
Service-to-service calls need authentication just like user calls, but there is no user to log in. The standard pattern is the OAuth 2.0 client credentials flow: each service has its own client id and secret, exchanges them at the authorization server for a short-lived access token, and sends that token as a bearer token to the downstream service, which validates it and checks the caller's scopes. Mutual TLS (mTLS) is the alternative or complement: each service presents a client certificate, so the connection itself proves identity and encrypts traffic — strong, but heavier to operate because of certificate management. In practice teams combine approaches: an API gateway authenticates external users once, internal calls use service tokens or mTLS, and the internal network is segmented so only known services can reach each other. The communication patterns themselves — synchronous REST versus asynchronous messaging — are covered in the companion post on microservices, Microservices Interview Questions for Java Developers; whatever the transport, the rule is the same: never trust a call just because it came from inside the network.
Example: The order service calls the payment service with a bearer token obtained via client credentials, scoped to payment:charge. The payment service validates the token signature and the scope before processing; a token without that scope is rejected with 403.
143. How do you troubleshoot login failures, invalid tokens and expired JWTs?
Start by separating the failure into authentication (401) or authorization (403), then work through the chain. For login failures, check the obvious first: the username exists, the password matches the stored hash (same encoder, same strength — a common bug is encoding the password twice or comparing a raw password with a hash), and the account is enabled and not locked. For invalid tokens, verify the signature with the same key and algorithm the issuer used, check the token has not been tampered with, and confirm the expected issuer and audience claims. For expired tokens, check the exp claim against the server clock — clock skew between services is a classic cause, and a small leeway (a minute or two) is standard. Enable debug logging for Spring Security (logging.level.org.springframework.security=DEBUG) to see which filter rejected the request and why, and decode the token at a tool such as jwt.io to inspect its claims — remembering that the payload is only base64, so never put secrets in it.
Example: A token that validates in development but fails in production usually means the signing key differs between environments; a token that fails intermittently often means clock skew between the issuing service and the validating service.
High Priority
144. What is the difference between session-based authentication and token-based authentication?
In session-based authentication the server keeps the session state: after login it creates a session, stores it (in memory or a store such as Redis), and gives the client a session id in a cookie. Every request sends the cookie, and the server looks the session up. In token-based authentication the server keeps no session state: after login it issues a signed token (usually a JWT), the client stores it and sends it with every request, and the server verifies the signature and reads the claims from the token itself. Sessions are easy to revoke (delete the session) and simple to reason about, but they need shared session storage to scale across instances and are vulnerable to CSRF when cookies are used. Tokens scale horizontally with no server state and work naturally for mobile clients and APIs, but they cannot be revoked without extra machinery (short expiry, refresh rotation, or a denylist) and they grow with the claims they carry. As a rule of thumb, sessions suit server-rendered web applications, tokens suit APIs and mobile clients.
Example: A browser app logs in and receives a JSESSIONID cookie; the server looks the session up on every request. A mobile app logs in and receives a JWT; the server verifies the signature on every request and holds no session for that user.
145. What are roles and authorities in Spring Security?
An authority is a single permission granted to a user, represented by a GrantedAuthority — typically a string such as ORDER_READ or ORDER_WRITE. A role is an authority with a naming convention: Spring Security treats any authority starting with ROLE_ as a role, so ROLE_ADMIN is the role ADMIN. The distinction matters in the authorization expressions: hasRole("ADMIN") checks for ROLE_ADMIN, while hasAuthority("ORDER_READ") checks the exact string. Roles are coarse-grained (what kind of user you are), authorities are fine-grained (what you may do). A common design is to assign users roles for broad access and check authorities for specific actions; mixing the two without a convention leads to rules that are hard to audit. In a JWT, roles and authorities usually travel as claims, and the filter that builds the Authentication converts them into GrantedAuthority objects.
Example:
.requestMatchers("/admin/**").hasRole("ADMIN") // needs ROLE_ADMIN
.requestMatchers(HttpMethod.GET, "/orders/**").hasAuthority("ORDER_READ")146. How do you implement method-level security?
Method-level security moves authorization from URL patterns into the service layer, where the rules can use method arguments and return values. Enable it with @EnableMethodSecurity (in Spring Security 6; the older @EnableGlobalMethodSecurity is deprecated), then annotate methods: @PreAuthorize runs before the method and can use SpEL expressions over the arguments and the authentication, @PostAuthorize runs after and can check the returned object, @Secured takes role names, and @RolesAllowed is the Jakarta standard equivalent. The expressions can also call beans, so a rule can ask a service whether the current user owns the resource being accessed. Method-level security is enforced by a proxy, so the same limits apply as with @Transactional: it works only on public methods called through the proxy, and self-invocation bypasses it.
Example:
@PreAuthorize("hasAuthority('ORDER_READ') and @orderSecurity.canRead(#id, authentication)")
public Order getOrder(Long id) { ... }
@PreAuthorize("hasRole('ADMIN')")
public void deleteOrder(Long id) { ... }147. How do you configure CORS and CSRF protection appropriately?
CORS and CSRF solve different problems and are configured differently. CORS is about which browser origins may call your API: configure it with a CorsConfigurationSource listing the allowed origins, methods, and headers, and wire it into Spring Security with http.cors() so the security filter chain applies it (a CORS bean alone is not enough when Security is on the classpath). CSRF protection is about preventing a malicious site from making a browser send a request with the user's cookies: Spring Security enables it by default, issuing a token that legitimate pages must include. For a stateless JWT API that authenticates with an Authorization header and no cookies, CSRF is not applicable — a malicious site cannot read the token to send it — so disabling CSRF there is correct, provided no cookie-based authentication exists. For a cookie-based browser application, keep CSRF enabled and send the token to the frontend. The common mistakes are disabling CSRF on a cookie-authenticated app and allowing all origins with credentials, which the browser rejects anyway.
Example:
http
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
.csrf(csrf -> csrf.disable()) // correct ONLY for a stateless token API
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS));148. How do you securely store passwords?
Passwords must never be stored in plain text or with a fast hash such as MD5 or SHA-256 alone, because those can be brute-forced quickly once a database leaks. The standard is an adaptive, salted password hash: BCrypt, scrypt, or Argon2. BCrypt is the default in Spring Security (BCryptPasswordEncoder): it generates a random salt per password, applies a configurable work factor (the cost parameter, typically 10–12, meaning 2^10–2^12 rounds), and stores the salt and cost inside the hash string, so verification needs no separate salt column. The work factor is a deliberate trade-off — higher is slower to attack but slower to verify, so measure login latency when raising it. When verifying, always use the encoder's matches(raw, stored) method, which extracts the salt and cost from the stored hash; never compare hashes with equals on re-encoded values, because the random salt makes the same password hash differently each time.
Example:
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(12); // cost 12: a few hundred ms per hash on typical hardware — measure login latency when raising it
}
// Store: passwordEncoder.encode(rawPassword)
// Check: passwordEncoder.matches(rawPassword, storedHash)149. How do you handle token revocation and logout in a JWT-based system?
JWTs are stateless, so there is no server-side session to delete — a valid token stays valid until it expires, which is the core revocation problem. The practical answer is layered. First, keep access tokens short-lived (minutes), so a leaked token dies quickly on its own. Second, revoke at the refresh-token level: store refresh tokens (or their hashes) server-side, delete them on logout, and rotate them on each use, so logging out kills the ability to get new access tokens. Third, for immediate revocation — a compromised account, a password change — keep a denylist of revoked token identifiers (jti claims) in Redis with a TTL equal to the token's remaining lifetime, and check it in the authentication filter; this adds a lookup per request, so use it only when immediate revocation is required. Logout itself is then two actions: the client deletes its stored tokens, and the server revokes the refresh token (and, if needed, denylists the access token). A system that claims JWTs are "revoked on logout" without any of this machinery is not actually revoking anything.
Example: On logout, the client deletes its tokens and calls POST /auth/logout; the server deletes the stored refresh token and adds the access token's jti to a Redis denylist with a 15-minute TTL, so the token stops working immediately.
Medium Priority
150. What is the difference between OAuth2 and OpenID Connect?
OAuth 2.0 is an authorization framework: it lets a user grant an application limited access to their resources on another service, without sharing their password. It says nothing about who the user is — it issues access tokens, not identity. OpenID Connect (OIDC) is an identity layer built on top of OAuth 2.0: it adds an ID token, a JWT containing claims about the user (subject, name, email), issued alongside the access token, plus a standard /userinfo endpoint and discovery document. In short, use OAuth 2.0 when you need delegated access to an API, and use OIDC when you need to know who the user is — which is the case for "Sign in with Google" and most login flows. If someone describes their login as "OAuth2", they almost always mean OIDC in practice.
Example: "Sign in with Google" is OIDC: Google returns an ID token with the user's email and name, which your application uses to create or find the account, and an access token, which it uses to call Google APIs.
151. What are common JWT security risks, including weak signing keys and excessive token claims?
The most common JWT risks are all avoidable. A weak or hard-coded signing key lets anyone forge tokens — use a long random key stored as a secret, and a strong algorithm such as HS256 with a 256-bit key or RS256 with a proper key pair; never accept the none algorithm, and always validate the algorithm in the token header against the one you expect. Overly long expiry turns a leaked token into a long-lived credential — keep access tokens to minutes. Excessive claims leak data: the payload is only base64-encoded, not encrypted, so anyone holding the token can read it — never put passwords, internal ids, or personal data in claims. Other risks include missing validation of the issuer (iss) and audience (aud) claims, which lets a token issued for another service be reused, and storing tokens in localStorage, where any cross-site scripting vulnerability can steal them — prefer httpOnly cookies or secure mobile storage. Finally, do not roll your own JWT code; use a maintained library.
Example: A rule instead of a contrived code sample: a token that carries only the user id, roles, expiry, and a token id, signed with a 256-bit key from the secret store and validated for algorithm, issuer, audience, and expiry, is the baseline; anything weaker is a finding in a security review.
5. Hibernate, JPA & Persistence
Very High Priority
152. What is the N+1 select problem, and how do you solve it?
The N+1 problem is the most common Hibernate performance bug. You run one query to load N parent entities, and then accessing a lazy association on each parent triggers one additional query per parent — 1 + N queries instead of 1 or 2. With 100 orders, loading each order's items costs 101 queries. The fixes all load the association eagerly in the original query. A fetch join in JPQL (JOIN FETCH) loads parents and children in one query. An @EntityGraph declares the same fetch plan on a repository method without writing JPQL. Batch fetching (@BatchSize or hibernate.default_batch_fetch_size) loads the associations in batches — 100 items in 10 queries of 10 instead of 100 queries of 1 — which is a good middle ground. A DTO projection avoids the problem entirely by selecting only the columns you need. The key interview point is recognizing the symptom: a page that runs hundreds of identical queries, visible in the SQL log, and knowing that the fix is fetching strategy, not a bigger database.
Example:
// N+1: 1 query for orders + 1 query per order for its items
List<Order> orders = orderRepository.findAll();
orders.forEach(o -> o.getItems().size());
// FIXED: one query loads orders and their items together
@Query("SELECT DISTINCT o FROM Order o JOIN FETCH o.items")
List<Order> findAllWithItems();153. What is the difference between lazy and eager loading?
Lazy loading defers loading an association until it is first accessed; eager loading loads it immediately together with the owning entity. Lazy is the default for collections (@OneToMany, @ManyToMany) and the right default for most associations: you pay only for what you use, and a list endpoint does not drag every related entity along. Eager is the default for single-valued associations (@ManyToOne, @OneToOne), because a single row is cheap to join — but eager on a collection is dangerous: it can produce cartesian products and load far more than the caller needs. The practical rule is to keep the defaults lazy where you can choose, and to override the fetch strategy per query (fetch join or entity graph) rather than changing the mapping globally — the mapping says what the relationship is, the query says what this particular use case needs. Accessing a lazy association outside a transaction is what causes LazyInitializationException, covered in the next question.
Example: Loading 50 orders with lazy items runs one query; the same load with eager items runs a join that returns every order row multiplied by its items, and accessing an unneeded eager association on a list endpoint is pure waste.
154. What is LazyInitializationException, why does it occur, and how do you resolve it?
LazyInitializationException means code tried to read a lazily loaded association after the persistence context (the session) was already closed. The typical sequence is: a service method loads an entity inside a transaction, the transaction commits and the session closes, and then the controller or the JSON serializer touches a lazy collection — Hibernate has no session left to load it with, so it throws. The clean fixes load the data while the session is still open: a fetch join or @EntityGraph on the query, or a DTO projection that selects exactly what the response needs. The quick fix is spring.jpa.open-in-view=true (Open EntityManager in View), which keeps the session open during view rendering — but it hides the problem, can trigger N+1 queries during serialization, and holds a database connection for the whole request, so it is considered a workaround rather than a solution. The interview answer is: fetch what you need inside the transaction, and do not let the serializer trigger lazy loading.
Example:
// THROWS: items are lazy, session closed when the controller serializes the response
@GetMapping("/orders/{id}")
public Order get(@PathVariable Long id) { return orderRepository.findById(id).orElseThrow(); }
// FIXED: load items inside the transaction with a fetch join
@Query("SELECT o FROM Order o JOIN FETCH o.items WHERE o.id = :id")
Optional<Order> findByIdWithItems(@Param("id") Long id);155. What are the entity lifecycle states in JPA/Hibernate?
A JPA entity is always in one of four states. Transient (new): the object exists in memory but is not associated with a persistence context and has no database identity — a new Order() before it is saved. Managed (persistent): the entity is associated with a persistence context, Hibernate tracks its changes, and dirty checking will write those changes to the database at flush time. Detached: the entity was managed, but its persistence context closed (or it was explicitly detached), so changes to it are no longer tracked — it still carries its database identity. Removed: the entity is marked for deletion and will be deleted at flush time. The transitions are: persist() moves transient to managed, merge() copies a detached entity's state onto a managed instance, remove() moves managed to removed, detach() moves managed to detached, and closing the EntityManager detaches everything it managed. Knowing the states matters because most JPA surprises — changes that do not save, exceptions on re-saving — are state mistakes.
The states and their transitions look like this:
Example: new Order() is transient; after entityManager.persist(order) it is managed, and changing its status is written to the database at flush without any explicit save call; after the transaction ends it is detached, and changing it further has no effect until it is merged back.
156. What is dirty checking, and when does Hibernate flush changes?
Dirty checking is Hibernate's automatic change tracking: for every managed entity, the persistence context keeps a snapshot of its state as loaded, and at flush time it compares the current state with the snapshot. Any field that changed produces an UPDATE — you never call a save method for a modification. A flush happens automatically before a query is executed (so the query sees your uncommitted changes), before the transaction commits, and when you call flush() explicitly. It is important to understand that a flush writes SQL to the database but does not commit the transaction — the changes are still rolled back if the transaction fails afterward. The practical consequences are that modifying a managed entity inside a @Transactional method is enough to persist the change, that an unexpected UPDATE in the logs usually means a managed entity was modified unintentionally, and that read-only transactions (@Transactional(readOnly = true)) skip dirty checking, which is a small performance win for pure reads.
Example:
@Transactional
public void renameOrder(Long id, String name) {
Order order = orderRepository.findById(id).orElseThrow();
order.setName(name); // no save() call — dirty checking writes the UPDATE at flush
}157. What is the difference between persist(), merge() and save()?
persist() and merge() are JPA EntityManager operations; save() is Spring Data JPA's repository method. persist() takes a transient entity and makes it managed: the same object instance becomes persistent, and it throws an exception if the entity already exists. merge() takes a detached entity, copies its state onto a managed instance (loading it from the database if needed), and returns that managed instance — the object you passed in stays detached, so changes to it afterward are ignored. save() is a convenience that delegates to one of the two: it calls persist() for a new entity and merge() for an existing one, deciding based on isNew(), which by default checks whether the id is null. The classic bug is calling merge() and then modifying the original object, expecting the changes to persist — they will not, because the returned managed copy is the one Hibernate tracks.
Example:
Order managed = entityManager.merge(detachedOrder); // use 'managed' from here on
managed.setStatus(OrderStatus.PAID); // tracked
detachedOrder.setStatus(OrderStatus.CANCELLED); // ignored — still detached158. What is the difference between first-level and second-level cache?
The first-level cache is the persistence context itself: every EntityManager keeps the entities it has loaded, keyed by id, for the duration of its session. It is mandatory, cannot be disabled, and is scoped to one session — a second EntityManager does not see it. Its main effect is identity: loading the same row twice in one session returns the same Java object. The second-level cache is shared across sessions and is optional: it sits between the EntityManager and the database, so an entity loaded by one session can be served from the cache to another. It needs a provider (such as Ehcache) and explicit configuration per entity (@Cacheable and a cache concurrency strategy), and it must be used carefully — cached entities can go stale when another application writes to the same database, so it suits read-mostly reference data, not rapidly changing transactional data. Query caching is a separate, also optional, cache for query results, and it is usually left off unless a specific repeated query justifies it.
Example: Product categories, loaded on almost every request and changed rarely, are good second-level-cache candidates; order rows, written constantly and read once, are not.
159. What is the difference between JPQL and native SQL?
JPQL (Java Persistence Query Language) queries entities, not tables: you write SELECT o FROM Order o WHERE o.status = :status, referring to the entity class and its fields, and Hibernate translates it to SQL for the underlying database. It is portable across databases and understands associations, inheritance, and the persistence context. Native SQL queries tables directly (SELECT * FROM orders WHERE status = ?): you get the full power of the database — window functions, database-specific syntax, complex reporting queries — but you lose portability and must map result rows to entities yourself (or accept them as Object[]). The rule of thumb is JPQL by default and native SQL when the database offers something JPQL cannot express, such as a recursive CTE or a vendor-specific function. In Spring Data JPA, @Query is JPQL unless you set nativeQuery = true.
Example:
// JPQL — portable, entity-based
@Query("SELECT o FROM Order o WHERE o.customer.id = :customerId")
List<Order> findByCustomer(@Param("customerId") Long customerId);
// Native SQL — database-specific, table-based
@Query(value = "SELECT * FROM orders WHERE status = :status LIMIT 10", nativeQuery = true)
List<Order> findRecentByStatus(@Param("status") String status);160. What is the difference between CascadeType and FetchType?
They answer two different questions about an association. CascadeType says which operations on the parent propagate to the child: PERSIST saves the child when the parent is saved, MERGE merges it, REMOVE deletes it when the parent is deleted, REFRESH refreshes it, DETACH detaches it, and ALL means all of them. FetchType says when the association is loaded: LAZY loads it on first access, EAGER loads it together with the parent. Confusing them is common but costly: cascading REMOVE on a @ManyToOne can delete a shared parent when one child is deleted, and marking a collection EAGER can load an entire object graph for a simple list query. The safe defaults are: cascade only where the child has no life of its own (an order line belongs to its order; a product does not belong to an order), and fetch lazily unless the query explicitly needs the association.
Example:
@OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true)
private List<OrderLine> lines; // lines live and die with the order
@ManyToOne(fetch = FetchType.LAZY)
private Customer customer; // loaded only when accessed161. What is the difference between EntityManager and Hibernate Session?
EntityManager is the JPA standard interface for working with the persistence context: persist, merge, remove, find, and creating queries. Session is Hibernate's native API, which offers everything the EntityManager does plus Hibernate-specific features such as filters, the legacy Criteria API, and saveOrUpdate. In a Spring Boot application you normally use the EntityManager (injected with @PersistenceContext) or Spring Data repositories, because the standard API is portable and sufficient; you reach for the Session with entityManager.unwrap(Session.class) only when you need a Hibernate-only feature. The EntityManager in Hibernate is implemented on top of a Session, so unwrapping is cheap and safe — but code that depends on the Session API is tied to Hibernate.
Example:
@PersistenceContext
private EntityManager entityManager;
// Hibernate-only feature, reached via unwrap:
Session session = entityManager.unwrap(Session.class);
session.enableFilter("activeOnly").setParameter("active", true);162. What is the difference between findById() and getReferenceById()?
Both load an entity by id, but they differ in when the database is hit. findById() executes a SELECT immediately and returns an Optional — empty if the row does not exist. getReferenceById() (the modern name for the older getOne()) returns a proxy without touching the database: the SELECT happens only when you first access the entity's state. The proxy is useful when you only need a reference — for example, setting an association before saving — because it avoids a query entirely. But it is a trap if the row does not exist: accessing the proxy then throws EntityNotFoundException, and using it outside a transaction can throw LazyInitializationException. As a rule of thumb, use findById() when you need the data or need to know whether it exists, and getReferenceById() only when you need a reference to set on another entity.
Example:
// Need the data: use findById()
Order order = orderRepository.findById(id).orElseThrow(() -> new OrderNotFoundException(id));
// Only need a reference to set the association: proxy avoids a SELECT
OrderLine line = new OrderLine();
line.setOrder(orderRepository.getReferenceById(orderId));163. How do you optimize Hibernate queries and control fetching?
Query optimization in Hibernate is mostly about controlling what is fetched and how much. First, fix the N+1 problem with fetch joins, entity graphs, or batch fetching, as in Q152. Second, fetch only what the use case needs: DTO projections select a few columns instead of whole entities, and lazy loading keeps unneeded associations out of the query. Third, paginate — never load an unbounded list. Fourth, check the generated SQL (enable spring.jpa.show-sql or, better, a SQL logger in development) and look for unexpected joins, cartesian products, or per-row queries. Fifth, use the second-level cache for read-mostly reference data, and consider a read model or a native query for reporting. Finally, remember that the mapping is not the query plan: keep mappings lazy and minimal, and decide the fetch strategy per query, where the actual need is visible.
Example: A rule instead of a contrived code sample: a dashboard that shows order id, total, and customer name should select those three columns into a DTO in one query, not load full Order entities with their items, payments, and history and then throw most of it away.
High Priority
164. What is the difference between save() and saveAndFlush()?
save() makes the entity managed — persisting a new one or merging a detached one — but it does not force the SQL to be sent to the database immediately. The INSERT or UPDATE is typically written at flush time, which happens before the next query or at transaction commit. saveAndFlush() does the same thing and then flushes immediately, so the SQL executes right away within the same transaction. The difference matters when later code in the same transaction depends on the row already existing in the database — for example, a native query that reads the row, or a database trigger or constraint that must fire now — or when you want a constraint violation to surface at a known point instead of at commit. Note that flushing is not committing: the changes are still rolled back if the transaction fails afterward. As a rule of thumb, use plain save() and let the transaction boundary handle flushing, and reach for saveAndFlush() only when something in the same transaction needs the row to be in the database already.
Example:
Order saved = orderRepository.save(order); // may not have hit the DB yet
Order flushed = orderRepository.saveAndFlush(order); // INSERT has executed now165. What is the difference between @OneToMany and @ManyToOne?
They are two sides of the same relationship. @ManyToOne sits on the "many" side: many orders belong to one customer, so the Order entity has a @ManyToOne Customer field, and the foreign key lives in the orders table. @OneToMany sits on the "one" side: one customer has many orders, so the Customer entity has a @OneToMany List<Order> field, usually with mappedBy pointing back to the owning field. The @ManyToOne side is the owning side — it holds the foreign key, and changes to it are what Hibernate persists. The @OneToMany side is normally the inverse side and is lazy by default, while @ManyToOne is eager by default. In a bidirectional mapping you set both sides in Java code to keep the object graph consistent, even though only the owning side affects the database.
Example:
@Entity
public class Order {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "customer_id")
private Customer customer; // owning side: the FK lives here
}
@Entity
public class Customer {
@OneToMany(mappedBy = "customer")
private List<Order> orders; // inverse side
}166. How do you map a many-to-many relationship?
A many-to-many relationship — students and courses, orders and tags — is mapped with @ManyToMany on both sides and a join table in between, defined with @JoinTable on the owning side (naming the table and the two foreign-key columns) and mappedBy on the inverse side. The join table holds only the two foreign keys. Two practical points matter. First, collections are lazy by default, so loading one side does not drag the other side along. Second, if the relationship itself needs extra data — an enrollment date, a quantity, a role — a plain join table cannot hold it, and the correct design is a link entity (for example Enrollment) with two @ManyToOne associations instead. Many-to-many mappings also deserve care with cascading: cascading REMOVE across a many-to-many can delete shared entities, so it is usually left off.
Example:
@Entity
public class Student {
@ManyToMany
@JoinTable(name = "student_course",
joinColumns = @JoinColumn(name = "student_id"),
inverseJoinColumns = @JoinColumn(name = "course_id"))
private Set<Course> courses;
}167. What is the owning side of a JPA relationship?
The owning side is the side of a bidirectional relationship that owns the foreign key (or the join table) and whose changes Hibernate actually persists. In a @OneToMany / @ManyToOne pair, the @ManyToOne side is the owner; the @OneToMany side is marked with mappedBy and is the inverse side. In a @ManyToMany pair, the side with @JoinTable owns the join table. The classic bug is updating only the inverse side — adding an order to customer.getOrders() without setting order.setCustomer(customer) — and finding that nothing is saved, because Hibernate ignores changes to the inverse side. The fix is a helper method on the parent that sets both sides, keeping the in-memory graph and the database in agreement.
Example:
public void addOrder(Order order) {
orders.add(order); // inverse side, for the in-memory graph
order.setCustomer(this); // owning side — this is what Hibernate persists
}168. What are orphanRemoval and cascade operations?
Both describe what happens to child entities when the parent changes, but they cover different triggers. Cascade operations propagate an explicit operation from parent to child: CascadeType.PERSIST saves the child when the parent is saved, MERGE merges it, REMOVE deletes it when the parent is deleted, REFRESH refreshes it, DETACH detaches it, and ALL applies all of them. orphanRemoval = true (available on @OneToMany and @OneToOne) handles a different event: when a child is removed from the parent's collection, the child is deleted from the database, even though nobody called remove() on it. Use cascade for "save/delete the children together with the parent" and orphan removal for "a child removed from the collection should cease to exist" — the classic case is order lines, which have no meaning without their order. The danger is applying either to a shared entity: orphan removal or cascade REMOVE on a relationship to a shared product would delete the product when one order drops it.
Example:
@OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true)
private List<OrderLine> lines;
// order.getLines().remove(line) — the line is deleted from the database at flush169. What is the difference between optimistic and pessimistic locking in JPA?
Optimistic locking assumes conflicts are rare: it does not lock anything in the database. Each entity carries a @Version field, and Hibernate includes the version in the UPDATE's WHERE clause; if another transaction changed the row first, the version no longer matches, no rows are updated, and Hibernate throws OptimisticLockException. The application then retries or reports the conflict. It scales well and is the default choice for most web applications. Pessimistic locking assumes conflicts are likely: it locks the row in the database at read time (LockModeType.PESSIMISTIC_WRITE issues SELECT ... FOR UPDATE), so other transactions block until the lock is released. It guarantees no lost update but holds database locks, risks deadlocks, and reduces concurrency. As a rule of thumb, optimistic locking for ordinary concurrent edits with a retry, pessimistic locking only when a lost update would be costly and contention is genuinely high, such as decrementing a small inventory count.
Example:
@Entity
public class Product {
@Version
private Long version; // Hibernate checks and increments this on every update
}
// Pessimistic alternative, when contention is high:
@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query("SELECT p FROM Product p WHERE p.id = :id")
Optional<Product> findByIdForUpdate(@Param("id") Long id);170. How do you implement pagination and sorting with Spring Data JPA?
This is the same Pageable API as Q104, so the mechanics are identical; the JPA-specific angle is what happens underneath and what it costs. A repository method taking a Pageable and returning Page<T> runs two queries: the page query with LIMIT/OFFSET (or the database's equivalent) and a count query for the total. The count query is the part people forget: on a large table it can be expensive, and if you do not need the total, return a Slice<T> instead, which checks only whether a next page exists. Sorting is expressed with Sort.by(...) and should always include a unique tiebreaker (usually the id) so the page boundaries are stable between requests. Also remember that offset pagination reads the skipped rows on every page, so deep pages get slower — for infinite scroll or very large tables, keyset pagination on the last seen id is the better design. The repository method itself is one line; the judgment is in choosing Page versus Slice and in keeping the sort deterministic.
Example:
// Page: two queries (rows + total count). Slice: one query, knows only "has next".
Slice<Order> slice = orderRepository.findByStatus(
OrderStatus.PAID,
PageRequest.of(0, 20, Sort.by("createdAt").descending().and(Sort.by("id"))));171. How do you avoid fetching unnecessary columns and relationships?
Loading whole entities and then using two fields is wasteful twice over: the database reads columns nobody needs, and Hibernate builds objects nobody uses. The fixes select only what is needed. A DTO projection — an interface-based projection or a constructor expression in JPQL (SELECT new com.shop.OrderSummary(o.id, o.total) FROM Order o) — returns exactly the fields the caller uses. A @Query that lists specific columns instead of SELECT * does the same in native SQL. For relationships, keep the defaults lazy and use a fetch join or entity graph only for the associations the current use case needs, rather than marking associations eager in the mapping. And for very wide tables, consider whether the entity should be split or whether a dedicated read model serves the query better. The habit to build is asking, for every repository call, "which columns and which associations does the caller actually use?" — and then fetching exactly those.
Example:
// Interface-based projection: only id and total are selected
public interface OrderSummary { Long getId(); BigDecimal getTotal(); }
List<OrderSummary> findSummariesByStatus(OrderStatus status);Medium Priority
172. What is the difference between JPA and Hibernate?
JPA (Jakarta Persistence, formerly Java Persistence API) is a specification: a set of interfaces and annotations — EntityManager, @Entity, JPQL — that describe how Java objects map to relational databases. Hibernate is the most widely used implementation of that specification, and it adds features beyond it, such as its own Session API, filters, custom types, and second-level cache integrations. Code written against the JPA interfaces is portable to another provider; code using Hibernate-specific features is not. In Spring Boot, spring-boot-starter-data-jpa brings Hibernate as the default provider, so most applications use JPA annotations and Hibernate behavior together without noticing the boundary. The interview line is simple: JPA is the contract, Hibernate is the engine that fulfills it — and knowing which side of the line a feature sits on tells you whether it will work on another JPA provider.
Example: @Entity and EntityManager.persist() are JPA and work on any provider; Session.enableFilter() and @BatchSize are Hibernate-specific and tie the code to Hibernate.
173. What is the purpose of @Entity and @Table?
@Entity marks a class as a JPA entity: Hibernate manages its lifecycle, maps it to a table, and tracks its changes. Without it, the class is a plain object that JPA ignores. @Table customizes the mapping to the table: its name sets the table name (otherwise the class name is used), schema and catalog place it in a specific schema, and uniqueConstraints declares constraints. Every entity needs an @Id field, and a no-argument constructor is required (it may be protected) because Hibernate instantiates entities reflectively. The annotations are small but load-bearing: a missing @Entity produces "not an entity" errors, and a wrong @Table(name) produces "table not found" errors at startup validation.
Example:
@Entity
@Table(name = "orders", schema = "shop")
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
// ...
}174. What is the difference between JPQL and Criteria API?
JPQL and the Criteria API express the same queries in different forms. JPQL is a string-based query language, close to SQL but over entities: readable, quick to write, and the right choice for fixed queries. The Criteria API builds the same query programmatically with a type-safe metamodel (CriteriaBuilder, Root, Predicate): verbose, but the compiler catches misspelled attribute names, and queries can be composed conditionally at runtime — add a predicate only when the caller supplied that filter. The trade-off is readability versus safety and dynamism: a fixed report query belongs in JPQL (or a @Query annotation), while a search screen with ten optional filters belongs in the Criteria API or in Spring Data's Specification API, which wraps it. Note that the Criteria API is verbose enough that teams often prefer QueryDSL, which generates a fluent type-safe API over the same ideas.
Example:
// JPQL: one line, fixed shape
@Query("SELECT o FROM Order o WHERE o.status = :status")
// Criteria API: composed at runtime — the status predicate is added only if supplied
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Order> query = cb.createQuery(Order.class);
Root<Order> root = query.from(Order.class);
if (status != null) {
query.where(cb.equal(root.get("status"), status));
}175. How do entity graphs and fetch joins help control query loading?
Both let you override the default fetch strategy for one specific query, without changing the entity mapping. A fetch join is written in JPQL (SELECT o FROM Order o JOIN FETCH o.items): it loads the association eagerly in the same query, which solves the N+1 problem for that query. An entity graph is declared with @EntityGraph on a repository method (or defined with @NamedEntityGraph on the entity): it names the associations to fetch, and the provider loads them eagerly for that query only, leaving the mapping's lazy defaults untouched elsewhere. Entity graphs are often preferred in Spring Data repositories because they need no JPQL — the method name or a simple @Query stays as it is, and the graph is an annotation on top. Both have the same limits: fetching several collections at once can produce a cartesian product, so fetch one collection per query and use batch fetching for the rest.
Example:
@EntityGraph(attributePaths = {"items", "customer"})
Optional<Order> findWithDetailsById(Long id);
// Loads the order, its items, and its customer in one query —
// without changing the lazy defaults on the entity itself.
Comments
Post a Comment