🚀 DAY 18 — Validation in Spring Boot (@Valid, Constraints) ✅ 1. CLEAR CONCEPT (VERY IMPORTANT) 👉 Validation = check input data before processing 👉 Example: Name should not be empty Email should be valid Age should be positive 💡 Without validation ❌ 👉 Wrong data enters system 💡 With validation ✅ 👉 Only correct data accepted ⚡ CORE ANNOTATIONS (IMPORTANT 🔥) Annotation Use @Valid Trigger validation @NotNullValue should not be null @NotBlank Not null + not empty @Size Length check @Email Valid email @Min / @Max Range check 💻 ENTITY EXAMPLE (VERY IMPORTANT) public class User { @NotBlank(message = "Name is required") private String name; @Email(message = "Invalid email") private String email; @Min(value = 18, message = "Age must be 18+") private int age; } ⚙️ CONTROLLER EXAMPLE @PostMapping("/users") public ResponseEntity<String> addUser(@Valid @RequestBody User user) { return ResponseEntity.ok("User added"); } 👉 If validation fails → error response 🔴 VALIDATION ERROR RESPONSE { "name": "Name is required", "email": "Invalid email" } 🎯 INTERVIEW QUESTIONS (MUST 🔥) ❓ What is @Valid? 👉 Used to trigger validation ❓ Difference: @NotNull vs @NotBlank? 👉 NotNull → value exists 👉 NotBlank → not null + not empty ❓ What is validation in Spring Boot? 👉 Checking input before processing ❓ Where do we use validation? 👉 In DTO / Entity class ⚡ BEST PRACTICES ✔ Always validate input ✔ Use meaningful messages ✔ Use DTO for validation 🔄 FLOW (IMPORTANT) 👉 Client → Request → Validation → Controller → Response 💡 FINAL UNDERSTANDING 👉 Validation = data safety 👉 @Valid = trigger validation 💬 Do you validate user input in your APIs? Day 18 done ✅ #SpringBoot #Java #BackendDevelopment #LearningInPublic #30DaysOfCode #Developers
Spring Boot Validation with @Valid and Constraints
More Relevant Posts
-
REST API Basics Every Developer Should Know 👇 GET → Fetch data POST → Create data PUT → Update full data PATCH → Update partial data DELETE → Remove data 💡 Bonus: Use proper HTTP status codes: 200 ✅ 201 ✅ 400 ❌ 500 ❌ Clean API = Professional developer 🚀 👉 Follow for backend mastery #restapi #backend #java #springboot #developers #coding #webdevelopment #softwareengineer #tech #learning #trending
To view or add a comment, sign in
-
🚦 Bean Validation vs Custom Validation in Spring Boot 1. Bean Validation (JSR-380) 👉 Built-in annotations to validate request data automatically ✔️ @NotNull, @NotBlank, @Size, @Email ✔️ Works with @Valid / @Validated ✔️ Clean, declarative, less boilerplate Why use? 1. Standardized validation 2. Faster development 3. Readable DTOs 2. Custom Validation 👉 When built-in annotations aren’t enough ✔️ Create your own annotation + validator ✔️ Handle complex business rules ✔️ Reusable across project Why use? 1. Domain-specific rules 2. Advanced logic (cross-field, DB checks) 3. Full control over validation Example 1. Bean: @NotBlank @Email private String email; 2. Custom: @ValidPassword private String password; Flow ⚙️ Request → DTO → Validation → Controller → Service Rule of Thumb 🧠 👉 Use Bean Validation for majority cases 👉 Use Custom Validation for business logic 👉 If you are preparing for Java backend interviews, connect & follow - I share short, practical backend concepts regularly. #SpringBoot #Java #Backend #Validation #CleanCode #RESTAPI #SoftwareEngineering #InterviewPrep
To view or add a comment, sign in
-
-
🚀 Day 23 – Logging Best Practices in Java: Build Systems You Can Debug at 3 AM Logging is your system’s black box recorder. Done well → it accelerates debugging, improves reliability, and strengthens observability. Done poorly → it becomes noise, slows performance, and hides root causes. Here are the best practices every architect should enforce: 🔹 1. Use the Right Log Levels ERROR → Something failed, needs attention WARN → Suspicious but system continues INFO → High-level business events DEBUG → Internal flow details TRACE → Too detailed, use sparingly ➡ Proper level usage prevents both noisy logs and missing insights. 🔹 2. Never Log Sensitive Data Avoid logging: ❌ Passwords ❌ Tokens ❌ Personal data ❌ Payment details ➡ Reduces compliance risk (PCI-DSS, GDPR) and enhances security. 🔹 3. Use Structured Logging Prefer JSON logs: {"event":"orderCreated","orderId":123,"amount":4500} ➡ Machine-readable logs enhance monitoring, searchability, and analytics. 🔹 4. Always Log With Context Include identifiers: ✔ userId ✔ orderId ✔ correlationId ✔ requestId ➡ Makes debugging distributed systems dramatically easier. 🔹 5. Avoid Log Spam No unnecessary logs like: ❌ "Entering method…" ❌ "Processing…" ❌ Repetitive debug statements ➡ Less noise → faster troubleshooting. 🔹 6. Use Parameterized Logging log.info("Order created: {}", orderId); ➡ Avoids string concatenation overhead. 🔹 7. Log Exceptions Properly Never do this: ❌ log.error(e.getMessage()); Always do this: ✔ log.error("Payment failed", e); ➡ Ensures stack traces are preserved. 🔹 8. Centralize Logs for Observability Use: ✔ ELK/EFK ✔ Splunk ✔ Datadog ✔ CloudWatch / Azure Log Analytics ➡ Unified logs = faster RCA & better system insights. 🔹 9. Correlate Logs Across Microservices Every request should carry a correlation ID all the way through. ➡ Helps visualize entire request flow. 🔥 Architect’s Takeaway Good logging is not optional — it’s a core part of system design. A well-logged system is: ✔ Easier to debug ✔ Safer ✔ More reliable ✔ More observable ✔ More performant #100DaysOfJavaArchitecture #Logging #Java #Microservices #SystemDesign #Observability #TechLeadership
To view or add a comment, sign in
-
-
💡 𝗝𝗮𝘃𝗮/𝐒𝐩𝐫𝐢𝐧𝐠 𝐁𝐨𝐨𝐭 𝗧𝗶𝗽 - 𝐌𝐢𝐬𝐬𝐢𝐧𝐠 𝐕𝐚𝐥𝐮𝐞𝐬 🔥 💎 𝗘𝘅𝗰𝗲𝗽𝘁𝗶𝗼𝗻 𝘃𝘀 𝗢𝗽𝘁𝗶𝗼𝗻𝗮𝗹 💡 𝗘𝘅𝗰𝗲𝗽𝘁𝗶𝗼𝗻𝘀 are designed for truly exceptional, unexpected errors that occur outside normal program flow. When thrown, they propagate up the call stack until caught by an appropriate handler. ✔ Exceptions should never be used for routine control flow due to significant performance costs from stack unwinding and object creation. 🔥 𝗢𝗽𝘁𝗶𝗼𝗻𝗮𝗹 provides an explicit alternative for representing absence of a value. It wraps a value that may or may not be present, making null-safe code more expressive and functional. ✔ Optional is ideal for modeling "value might be missing" scenarios and works seamlessly with streams and lambda expressions. ✅ 𝗪𝗵𝗲𝗻 𝘁𝗼 𝗨𝘀𝗲 𝗘𝗮𝗰𝗵 ◾ 𝗘𝘅𝗰𝗲𝗽𝘁𝗶𝗼𝗻𝘀: Rare failures like I/O errors, database connection issues, or invalid business transactions. ◾ 𝗢𝗽𝘁𝗶𝗼𝗻𝗮𝗹: Expected absence like cache misses, lookup results not found, or optional configuration values. ◾ 𝗛𝘆𝗯𝗿𝗶𝗱 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵: Use both strategically for optimal code clarity and performance. 🤔 Which approach do you prefer for handling missing values? #java #springboot #programming #softwareengineering #softwaredevelopment
To view or add a comment, sign in
-
-
Recently, I’ve been working on backend automation using Spring Boot and Java, focusing on improving how structured data flows between systems. A big part of the challenge has been handling semi-structured inputs and transforming them into consistent, usable data for downstream processes. Some of the areas I’ve been exploring: • Extracting metadata through tagging strategies • Working with hybrid data models (structured entities + flexible JSON) • Designing logic that adapts based on the available data instead of forcing rigid structures • Building automation flows that stay maintainable as requirements evolve This experience has pushed me to think more about trade-offs in data modeling and how to design systems that are resilient to change. Always interested in connecting with others working on backend systems, automation, or data-driven workflows. #Java #SpringBoot #BackendDevelopment #Automation #SoftwareEngineering
To view or add a comment, sign in
-
Streams look simple. But most developers don’t understand how they actually work. A Java Stream is not a data structure. It is a pipeline of operations applied to data. Think like this: Collection → Stream → Operations → Result There are 3 important parts: 1. Source List, Set, or any collection 2. Intermediate operations filter() → removes unwanted data map() → transforms data sorted() → orders data These are lazy → they don’t run immediately 3. Terminal operations collect() → gather result forEach() → process items reduce() → combine values These actually trigger execution That means: Nothing runs until a terminal operation is called Example mindset: numbers.stream() → filter even numbers → double them → collect result This runs as a single pipeline, not multiple loops. That is why Streams are powerful: less boilerplate more readable optimized execution supports parallel processing But also remember: Streams are not always faster. Use them for clarity and transformation, not blindly everywhere. Best way to think: Streams = “what to do” Loops = “how to do” Which Stream method confused you most: filter, map, or reduce? #Java #JavaStreams #BackendDevelopment #SoftwareEngineering #Programming #TechLearning #CleanCode #JavaDeveloper #CodingTips #DeveloperJourney
To view or add a comment, sign in
-
-
Most developers equate slow APIs with bad code. However, the issue often lies elsewhere. Consider this scenario: You have a query that appears perfectly fine: SELECT o.id, c.name FROM orders o JOIN customers c ON o.customer_id = c.id Yet, the API is painfully slow. Upon checking the execution plan, you find: NESTED LOOP → TABLE ACCESS FULL ORDERS → INDEX SCAN CUSTOMERS At first glance, this seems acceptable. But here's the reality: for each row in orders, the database is scanning and filtering again. If orders contain 1 million rows, that's 1 million loops. The real issue wasn’t the JOIN; it was the database's execution method. After adding an index: CREATE INDEX idx_orders_date ON orders(created_at); The execution plan changed to: INDEX RANGE SCAN ORDERS → INDEX SCAN CUSTOMERS As a result, query time dropped significantly. Key lessons learned include: • Nested Loop is efficient only when: → the outer table is small → the inner table is indexed • Hash Join is preferable when: → both tables are large → there are no useful indexes • Common performance issues stem from: → full table scans → incorrect join order → missing indexes → outdated statistics A common mistake is this Java code: for (Order o : orders) { o.getCustomer(); } This essentially creates a nested loop at the application level (N+1 query problem). Final takeaway: Don’t just write queries; understand how the database executes them. That's where true performance improvements occur. If you've resolved a slow query using execution plans, sharing your experience would be valuable. #BackendDevelopment #DatabaseOptimization #SQLPerformance #QueryOptimization #SystemDesign #SoftwareEngineering #Java #SpringBoot #APIPerformance #TechLearning #Developers #Coding #PerformanceTuning #Scalability #DistributedSystems #DataEngineering #Debugging #TechTips #LearnInPublic #EngineeringLife
To view or add a comment, sign in
-
🚀 DAY 17 — ResponseEntity & Exception Handling ✅ 1. CLEAR CONCEPT (VERY IMPORTANT) 🔹 ResponseEntity 👉 Used to return: Data Status code Headers 💡 Instead of just returning data, 👉 you return complete HTTP response 🔹 Example @GetMapping("/user") public ResponseEntity<String> getUser() { return ResponseEntity.ok("User found"); } 👉 Response: Body → "User found" Status → 200 OK ⚡ WHY USE ResponseEntity? ✔ Control status code ✔ Custom response ✔ Better API design 🔴 EXCEPTION HANDLING (VERY IMPORTANT) 👉 Handles errors in clean way ❌ Without Exception Handling 👉 App crashes or messy error ✅ With Exception Handling 👉 Clean error response 💻 EXAMPLE (IMPORTANT 🔥) @GetMapping("/user/{id}") public ResponseEntity<String> getUser(@PathVariable int id) { if (id == 0) { throw new RuntimeException("User not found"); } return ResponseEntity.ok("User found"); } ⚙️ GLOBAL EXCEPTION HANDLER @RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(RuntimeException.class) public ResponseEntity<String> handleException(RuntimeException ex) { return ResponseEntity .status(404) .body(ex.getMessage()); } } 🎯 INTERVIEW QUESTIONS (MUST 🔥) ❓ What is ResponseEntity? 👉 Used to return full HTTP response ❓ Why use ResponseEntity? 👉 To control status + response ❓ What is Exception Handling? 👉 Handling errors gracefully ❓ What is @RestControllerAdvice? 👉 Global exception handler ❓ What is @ExceptionHandler? 👉 Handles specific exception ⚡ COMMON STATUS CODES Code Meaning 200 OK 201 Created 400 Bad Request 404 Not Found 500 Server Error 💡 BEST PRACTICES ✔ Always use ResponseEntity ✔ Handle exceptions globally ✔ Return proper status codes 🔄 FLOW (IMPORTANT) 👉 Client → API → Exception → Handler → Response 💡 FINAL UNDERSTANDING 👉 ResponseEntity = control response 👉 Exception Handling = control errors 💬 Do you return proper status codes in your APIs? Day 17 done ✅ #SpringBoot #Java #BackendDevelopment #LearningInPublic #30DaysOfCode #Developers
To view or add a comment, sign in
-
-
🚀 𝗝𝗮𝘃𝗮 𝟴 𝗦𝘁𝗿𝗲𝗮𝗺𝘀 – 𝗜𝗻𝘁𝗲𝗿𝗺𝗲𝗱𝗶𝗮𝘁𝗲 𝗖𝗼𝗻𝗰𝗲𝗽𝘁𝘀 𝗘𝘃𝗲𝗿𝘆 𝗗𝗲𝘃𝗲𝗹𝗼𝗽𝗲𝗿 𝗦𝗵𝗼𝘂𝗹𝗱 𝗠𝗮𝘀𝘁𝗲𝗿 Streams revolutionized how we process collections in Java. Once you’re comfortable with the basics, it’s time to explore the intermediate concepts that unlock their full potential: 1️⃣ 𝗟𝗮𝘇𝘆 𝗘𝘃𝗮𝗹𝘂𝗮𝘁𝗶𝗼𝗻 Operations like 𝘧𝘪𝘭𝘵𝘦𝘳() and 𝘮𝘢𝘱() don’t run until a terminal operation (collect(), reduce(), etc.) is invoked. This allows efficient, optimized pipelines. 2️⃣ 𝗣𝗮𝗿𝗮𝗹𝗹𝗲𝗹 𝗦𝘁𝗿𝗲𝗮𝗺𝘀 Use parallelStream() to leverage multi-core processors for heavy computations. Great for CPU-intensive tasks, but be mindful of thread safety and overhead. 3️⃣ 𝗖𝗼𝗹𝗹𝗲𝗰𝘁𝗼𝗿𝘀 𝗳𝗼𝗿 𝗔𝗱𝘃𝗮𝗻𝗰𝗲𝗱 𝗚𝗿𝗼𝘂𝗽𝗶𝗻𝗴 The Collectors utility class enables powerful aggregations: groupingBy() → classify data partitioningBy() → split by boolean condition joining() → concatenate strings 4️⃣ 𝗥𝗲𝗱𝘂𝗰𝘁𝗶𝗼𝗻 𝗢𝗽𝗲𝗿𝗮𝘁𝗶𝗼𝗻𝘀 Beyond built-in collectors, reduce() lets you define custom aggregation logic. Example: finding the longest string in a list. 5️⃣ 𝗙𝗹𝗮𝘁𝗠𝗮𝗽 𝗳𝗼𝗿 𝗡𝗲𝘀𝘁𝗲𝗱 𝗦𝘁𝗿𝘂𝗰𝘁𝘂𝗿𝗲𝘀 Flatten lists of lists into a single stream for easier processing. 6️⃣ 𝗖𝘂𝘀𝘁𝗼𝗺 𝗖𝗼𝗹𝗹𝗲𝗰𝘁𝗼𝗿𝘀 Build specialized collectors with Collector.of() when default ones don’t fit your use case. ⚠️ 𝗕𝗲𝘀𝘁 𝗣𝗿𝗮𝗰𝘁𝗶𝗰𝗲𝘀 • Avoid side effects inside streams. • Use parallel streams wisely (not for small or I/O-bound tasks). • Prefer immutability when working with streams. 💡 Mastering these intermediate concepts makes your Java code more expressive, efficient, and scalable. 👉 Which stream feature do you find most powerful in your projects? #Java #Streams #FunctionalProgramming #IntermediateConcepts #DevTips #CleanCode
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development