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

๐Ÿ” Is final Really Final in Java? The Truth May Surprise You ๐Ÿ˜ฒ

๐Ÿ’ฌ “When I was exploring what to do and what not to do in Java, one small keyword caught my eye — final . I thought it meant: locked, sealed, frozen — like my fridge when I forget to defrost it.”   But guess what? Java has its own meaning of final… and it’s not always what you expect! ๐Ÿ˜… Let’s break it down together — with code, questions, confusion, jokes, and everything in between. ๐ŸŽฏ The Confusing Case: You Said It's Final... Then It Changed?! ๐Ÿซ  final List<String> names = new ArrayList <>(); names.add( "Anand" ); names.add( "Rahul" ); System.out.println(names); // [Anand, Rahul] ๐Ÿคฏ Hold on... that’s final , right?! So how on earth is it still changing ? Time to dive deeper... ๐Ÿง  Why Is It Designed Like This? Here’s the key secret: In Java, final applies to the reference , not the object it points to . Let’s decode this like a spy mission ๐Ÿ•ต️‍♂️: Imagine This: final List<String> names = new ArrayList <>(); Be...

๐ŸŒŸ My Journey – From Zero to Senior Java Tech Lead ๐ŸŒŸ

 There’s one thing I truly believe… If I can become a Java developer, then anyone in the world can. ๐Ÿ’ฏ Sounds crazy? Let me take you back. ๐Ÿ•“ Back in 2015… I had zero coding knowledge . Not just that — I had no interest in coding either. But life has its own plans. In 2016, I got a chance to move to Bangalore and joined a Java course at a training center. That’s where it all started — Every day, every session made me feel like: "Ohhh! Even I can be a developer!" That course didn’t just teach Java — it gave me confidence . ๐Ÿงช Two Life-Changing Incidents 1️⃣ The Interview That Wasn't Planned Halfway through my course, I had to urgently travel to Chennai to donate blood to a family member. After that emotional rollercoaster, I found myself reflecting on my skills and the future. The next day, as I was preparing for my move to Bangalore to complete the remaining four months of my course, I randomly thought — "Let me test my skills... let me just see...

๐ŸŽข Java Loops: Fun, Fear, and ForEach() Fails

๐ŸŒ€ Oops, I Looped It Again! — The Ultimate Java Loop Guide You Won't Forget “I remember this question from one of my early interviews — I was just 2 years into Java and the interviewer asked, ‘Which loop do you prefer and why?’” At first, I thought, “Duh! for-each is cleaner.” But then he grilled me with cases where it fails. ๐Ÿ˜ต That led me to explore all loop types, their powers, and their pitfalls. Let’s deep-dive into every major Java loop with examples &  real-world guidance so you'll never forget again. ๐Ÿ” Loop Type #1: Classic For Loop — “The Old Reliable” ✅ When to Use: You need an index You want to iterate in reverse You want full control over loop mechanics ✅ Good Example: List<String> names = List.of("A", "B", "C"); for (int i = 0; i < names.size(); i++) { System.out.println(i + ": " + names.get(i)); } ๐Ÿ”ฅ Reverse + Removal Example: List<String> item...