Skip to main content

🌟 @Valid vs @Validated in Spring Boot — The Complete Guide with Fun Examples πŸŽ­πŸ’‘ 🌟

πŸ€” Extra or Missing Fields in JSON? The Untold Spring Boot Story!

Have you ever sent a JSON request from Postman thinking, “Ah, backend will understand me!”… only to later find out half your fields vanished into thin air? πŸ˜…


🎯 Scenario 1 — Missing Fields in Request



public class Employee {

    private String name;

    private String department;

    private int age;

    private String email;

}

Postman JSON:



{

  "name": "Alice",

  "department": "HR"

}

Result:

FieldValue
nameAlice
departmentHR
age0 (default int)
emailnull

πŸ“ Why? Jackson only maps what it sees in JSON. The rest remain null (or default for primitives).


🎯 Scenario 2 — Extra Fields in Request



public class Employee {

    private String name;

    private String department;

}

Postman JSON:



{

  "name": "Bob",

  "department": "Finance",

  "age": 30,

  "location": "London"

}

Result: Only name and department are populated. age and location vanish like that friend who said “I’ll be there in 5 minutes” ⏳πŸ˜‚


πŸ” Who’s Doing the Magic?

  • Spring MVC receives the request πŸ“¬
  • MappingJackson2HttpMessageConverter turns JSON → Java
  • Jackson’s ObjectMapper maps matching fields
  • Unknown fields are ignored (by default)

🚫 When Will It Throw an Error?

  1. Global Config: spring.jackson.deserialization.fail-on-unknown-properties=true
  2. Per Class: @JsonIgnoreProperties(ignoreUnknown = false)
  3. Data type mismatch (e.g., sending "thirty" for an int)
  4. Using constructor/record without matching parameters
  5. Bean Validation failures (@NotNull, @Valid)

✅ Validating Missing Fields



import jakarta.validation.constraints.NotNull;

public class Employee {

    @NotNull(message = "Name is required")

    private String name;

    @NotNull(message = "Department is required")

    private String department;

}

Controller:



import org.springframework.validation.annotation.Validated;

@RestController

@Validated // Needed for method-level validation

public class EmployeeController {

    @PostMapping("/create")

    public ResponseEntity create(@Valid @RequestBody Employee employee) {

        // validation happens before this line

        return ResponseEntity.ok("Employee created");

    }

}

πŸ’‘ Important:

  • For request body DTO validation, @Valid alone is enough on the method parameter.
  • For method-level validation inside the same bean, you must also add @Validated on the class.


πŸ“ Best Practices

  • Use DTOs instead of directly binding to entities
  • Validate with @Valid and Bean Validation
  • Enable strict mode in dev/test, allow leniency in prod during deployments
  • Document your API to avoid “ghost fields” πŸ‘»

🎀 Interview Q&A Corner

Q: What happens if your JSON request has more fields than your DTO?

A: By default, extra fields are ignored by Jackson.

Q: How can you make Spring Boot fail on unknown fields?

A: Use spring.jackson.deserialization.fail-on-unknown-properties=true or @JsonIgnoreProperties(ignoreUnknown = false).

Q: How do you enforce certain fields to always be present?

A: Add @NotNull with @Valid and, if validating inside the same bean, also @Validated at the class level.

Q: Which Spring component handles JSON → Java object mapping?

A: MappingJackson2HttpMessageConverter with Jackson’s ObjectMapper.


πŸŒ€ Wrapping Up

Today we busted a common myth — extra fields in JSON won’t break your Spring Boot app unless you tell them to. Missing fields? They just become null or default values. But remember — just because your app doesn’t break, doesn’t mean your data is correct! 🧐

πŸ’¬ Have you ever chased a bug for hours, only to find out the frontend was sending “bonus” fields the backend never saved? Share your story in the comments — let's laugh (and cry) together! πŸ˜‚

Comments

Popular posts from this blog

🐱 Tomcat vs ⚡ Netty – Which One Should You Use?

🐱 Tomcat vs ⚡ Netty – Which One Should You Use? So recently I got curious about this too πŸ€”. Everywhere in Spring Boot tutorials we see Tomcat . Then suddenly while exploring Spring WebFlux , the name Netty pops up. And I was like – “Wait, who’s this Netty guy trying to replace Tomcat?” πŸ˜… Let’s break it down with real-time examples , icons , and fun comparisons . 🐱 Tomcat – The Traditional Web Server Type: Servlet Container (blocking I/O) World: Used with Spring MVC Style: Thread-per-request model πŸ‘©‍πŸ’» Pros: Stable, widely used, battle-tested Cons: Struggles with huge concurrent connections πŸ‘‰ Example in real life: Tomcat is like a restaurant with fixed waiters 🍴. - Each customer = one thread/waiter - If too many customers come in at once → waiters run out → customers wait outside πŸšͺ ⚡ Netty – The Reactive Rockstar Type: Asynchronous Event-Driven Network Framework World: Default for Spring WebFlux Style: Event-lo...

🎭 Spring’s Secret: Why @Transactional & Friends Betray You Silently

πŸ’‘ Lesson Learned — Not a Prod Bug, But a Real Pain No, this wasn’t a production outage. Nobody screamed at me. But I sat for 3 hours wondering: “Why the heck is my @Transactional not rolling back!?” 😡‍πŸ’« “Why is Redis cache not working?” 🀯 Turned out, the issue was one silent villain: 🧱 Self-invocation 🀷 What Is @Transactional ? If you're new: @Transactional = Tells Spring to start a DB transaction when a method is called. It’ll commit if everything’s okay. It’ll rollback if something fails. 🧠 Think of it like wrapping your code in: try { beginTransaction(); // your logic commit(); } catch(Exception e) { rollback(); } πŸ•΅️ Real-Life Analogy — The Gateway Community 🏘️ Let me tell you about my society — it has a strict watchman at the gate. Here’s how it works: πŸ›‚ Watchman = Spring Proxy 🏠 Your apartment = Your service class πŸšͺ Your room = A method inside that class πŸƒ Scenario 1: Outsider Visits Your friend from outside...

🧡 Virtual Threads in Java — The Ultimate Guide with Diagrams, Code & Interview Qs!

πŸš€ “How are Virtual Threads different from Thread Pools?” 😡 “Are they OS threads or JVM threads?” πŸ™ƒ “Should I still use CompletableFuture?” 🀯 “How do I even use them in real-time microservices?” 🧠 What are Virtual Threads? Virtual Threads (introduced in Java 21 as stable πŸŽ‰) are lightweight threads managed by the JVM instead of the OS kernel. πŸ‘‰ They look like normal threads, but don’t hog OS resources like traditional threads. 🧠 What is the OS Kernel? πŸ›️ OS Kernel = The Brain of the Operating System It’s the core part of your OS (Windows, Linux, Mac) that: Manages memory 🧠 Schedules threads πŸ•’ Talks to hardware πŸ’» Handles I/O operations πŸ“¨ When you create a traditional thread in Java, the JVM asks the OS Kernel to create a real OS-level thread. πŸ–Ό️ Imagine This... ┌───────────────────────────┐ │ Your Java Application │ └────────────┬──────────────┘ │ ...