#Post4 In the previous post, we understood how request mapping works using @GetMapping and others. Now the next question is 👇 How does Spring Boot handle data sent from the client? That’s where @RequestBody comes in 🔥 When a client sends JSON data → it needs to be converted into a Java object. Example request (JSON): { "name": "User", "age": 25 } Controller: @PostMapping("/user") public User addUser(@RequestBody User user) { return user; } 👉 Spring automatically converts JSON → Java object This is done using a library called Jackson (internally) 💡 Why is this useful? • No manual parsing needed • Clean and readable code Key takeaway: @RequestBody makes it easy to handle request data in APIs 🚀 In the next post, we will understand @PathVariable and @RequestParam 🔥 #Java #SpringBoot #BackendDevelopment #RESTAPI #LearnInPublic
Spring Boot @RequestBody handles JSON data conversion
More Relevant Posts
-
🚀 Day 19 – map() vs flatMap() in Java Streams While working with Streams, I came across a subtle but important difference: "map()" vs "flatMap()". --- 👉 map() Transforms each element individually List<String> names = Arrays.asList("java", "spring"); names.stream() .map(String::toUpperCase) .forEach(System.out::println); ✔ Output: JAVA, SPRING --- 👉 flatMap() Flattens nested structures List<List<Integer>> list = Arrays.asList( Arrays.asList(1, 2), Arrays.asList(3, 4) ); list.stream() .flatMap(Collection::stream) .forEach(System.out::println); ✔ Output: 1, 2, 3, 4 --- 💡 Key insight: - "map()" → 1-to-1 transformation - "flatMap()" → 1-to-many (and then flatten) --- ⚠️ Real-world use: "flatMap()" is very useful when dealing with: - Nested collections - API responses - Complex data transformations --- 💡 Takeaway: Understanding when to use "flatMap()" can make your stream operations much cleaner and more powerful. #Java #BackendDevelopment #Java8 #Streams #LearningInPublic
To view or add a comment, sign in
-
🚀 Day 23/100: Spring Boot From Zero to Production Topic: @RequestBody & @ResponseBody Spring is Annotations And It Goes On.... We've established this pattern by now. And these two? Pretty self-explanatory once you see them in action. @RequestBody, Catching What the Client Sends 📥 1. Annotated at the method parameter level 2. Client sends a JSON body with Content-Type: application/json 3. Spring maps that JSON → a DTO you defined in your business layer 4. That's Jackson doing the heavy lifting behind the scenes 5. Bonus: pairs perfectly with @Valid and @Validated for input validation @ResponseBody, Sending Back What the Client Needs 📤 1. Works at the class level (mostly) 2. You rarely write it explicitly — it comes bundled inside @RestController 3. Serializes your return value → JSON response the client receives 4. Also plays nicely with ResponseEntity for full control over status codes and headers The Short Version @RequestBody → JSON in → Java object @ResponseBody → Java object → JSON out @RestController = @Controller + @ResponseBody already baked in One annotation does the reading. One does the writing. Spring handles the rest. Pretty simple, right? #Java #SpringBoot #SoftwareDevelopment #100DaysOfCode #RestAPI
To view or add a comment, sign in
-
-
🚀 Exchanger in Java – Why It’s Important 🔄 In multithreading, sometimes threads don’t just wait — they exchange data efficiently. That’s where Exchanger from Java comes in 💡 🔹 Why it matters? ✅ Direct data swap between two threads 🤝 ✅ No extra queues or shared memory 🧠 ✅ Faster & cleaner communication ⚡ ✅ Ideal for paired thread tasks 👯 💡 Easy Real-Time Example 😄 Think of a chef 👨🍳 and waiter 🧑🍽️: 🍳 Chef prepares food 🍽️ Waiter serves food 👉 Chef gives dish 🍲 👉 Waiter returns empty tray 🧺 👉 Work continues instantly ⚡ 🔥 Fast | Clean | Efficient 💡 Another Simple Tech Example 💻 🧵 Thread A → Writing logs 📝 🧵 Thread B → Saving logs to file 💾 🔄 They exchange buffers: ➡️ One gives filled buffer ➡️ Other returns empty buffer No delay ⏱️ No extra memory overhead 📉 🛠️ Code Example import java.util.concurrent.Exchanger; Exchanger<String> exchanger = new Exchanger<>(); new Thread(() -> { try { String data = "🍔 Food"; data = exchanger.exchange(data); System.out.println("Chef got: " + data); } catch (Exception e) {} }).start(); new Thread(() -> { try { String data = "🧺 Tray"; data = exchanger.exchange(data); System.out.println("Waiter got: " + data); } catch (Exception e) {} }).start(); ⚡ Final Thoughts 💭 ✨ Sometimes the simplest tools create the biggest impact ✨ Clean thread communication = better performance ⚡ ✨ Less complexity = fewer bugs 🐞 ✨ Right synchronizer at the right place = scalable systems 📈 ✨ Small concepts like this can level up your system design thinking 🧠🔥 #Java #Multithreading #Concurrency #JavaDeveloper #BackendDevelopment #SoftwareEngineering #SystemDesign #Coding #TechLearning #Performance 🚀
To view or add a comment, sign in
-
🚀 Day 11: Scope & Memory – Mastering Variable Types in Java 🧠📍 Today’s focus was on understanding where data lives in a program—a crucial step toward writing efficient and predictable code. In Java, the way a variable is declared directly impacts its scope, lifetime, and memory allocation. Here’s how I broke it down: 🔹 1. Local Variables – Temporary Workers ⏱️ • Declared inside methods • Accessible only within that method • Created when the method starts, destroyed when it ends • ⚠️ Must be initialized before use (no default values) 🔹 2. Instance Variables – Object Properties 🏠 • Declared inside a class, outside methods • Require an object to access • Each object gets its own copy • Changes in one object do NOT affect another 🔹 3. Static Variables – Shared Data 🌐 • Declared with the static keyword • Belong to the class, not objects • Accessed using the class name (no object needed) • Only one copy exists, shared across all instances 💡 Key Takeaway: Variable scope is more than just visibility—it’s about memory management and data control. Knowing where and how variables exist helps in building optimized and scalable applications. Step by step, I’m strengthening my foundation in Java and moving closer to writing production-level code. 💻 #JavaFullStack #CoreJava #CodingJourney #VariableScope #MemoryManagement #Day11 #LearningInPublic
To view or add a comment, sign in
-
🚀 How HashMap Works Internally (In Simple Words) Most developers use HashMap daily… But very few actually understand what happens behind the scenes. 👀 Let’s break it down 👇 👉 1️⃣ Hashing – The Core Idea When you put a key-value pair into a HashMap: 👉 Java converts the key into a number using a hash function (hashCode()). Think of it like: 🔑 Key → 🔢 Hash → 📦 Bucket 👉 2️⃣ Bucket Storage HashMap has an array of buckets. The hash determines which bucket your data goes into. 👉 Index = hash % array size 👉 3️⃣ Collision Handling (Important 🔥) Sometimes multiple keys get the same bucket 😱 This is called a collision HashMap handles it using: ✔️ Linked List (before Java 8) ✔️ Balanced Tree (after Java 8, for better performance) 👉 4️⃣ Retrieval (get operation) When you do map.get(key) 👉 Same hashing process happens Then: ✔️ Go to the correct bucket ✔️ Search inside (list/tree) ✔️ Match using equals() 👉 5️⃣ Performance ⚡ Average time complexity: ✔️ Put → O(1) ✔️ Get → O(1) Worst case (many collisions): ❌ O(n) → improved to O(log n) in Java 8 👉 6️⃣ Load Factor & Resizing When HashMap gets too full: 👉 It resizes (doubles capacity) Default load factor = 0.75 Meaning: resize when 75% full 💡 Real Insight: A good hashCode() implementation = better performance 🚀 🔥 Final Thought HashMap looks simple from outside… But internally it’s a smart combination of: ➡️ Arrays ➡️ Hashing ➡️ Linked Lists / Trees 💬 Have you ever faced HashMap collision issues? #Java #DSA #Programming #BackendDevelopment #InterviewPrep
To view or add a comment, sign in
-
-
🚀 Java Records — Clean, Concise, and Immutable Data Models Tired of writing boilerplate code for simple data carriers in Java? That’s exactly where Java Records shine ✨ 👉 Introduced in Java 14 (finalized in Java 16), records provide a compact way to model immutable data. 🔹 What is a Record? A record is a special type of class designed to hold data — no unnecessary getters, setters, equals(), hashCode(), or toString() needed. 🔹 Example: java public record User(String name, int age) {} That’s it. Java automatically generates: ✔️ Constructor ✔️ Getters (name(), age()) ✔️ equals() & hashCode() ✔️ toString() 🔹 Why use Records? ✅ Less boilerplate → more readability ✅ Immutable by default → safer code ✅ Perfect for DTOs, API responses, and data transfer ✅ Encourages clean architecture 🔹 Custom logic? You still can: java public record User(String name, int age) { public String nameInUpperCase() { return name.toUpperCase(); } } 🔹 Important points: ⚠️ Fields are final ⚠️ Cannot extend other classes (but can implement interfaces) ⚠️ Best suited for data carriers, not business-heavy objects 💡 When to use? - Microservices DTOs - API request/response models - Immutable configurations 👉 Records are a step toward more expressive and maintainable Java code. Are you using records in your projects yet? 🤔 #Java #Java17 #BackendDevelopment #CleanCode #SoftwareEngineering #FullStackDev
To view or add a comment, sign in
-
🚨 My code was fine… my configuration was the problem. Day 40 of my Backend Developer Journey — and today felt like a real developer day 🧠 LeetCode Breakthrough Solved a problem using mathematical optimization (Rotation Function) 💡 What clicked: → Reuse previous computation → Avoid recalculating entire function → Derive relation between rotations ⚡ The Real Trick 👉 Instead of O(n²), use: F(k) = F(k-1) + sum - n × last_element 🔍 Key Insight 👉 Precompute total sum 👉 Build answer iteratively 👉 Turn brute force into O(n) 🔗 My Submission: https://lnkd.in/gRWYfwKj ☕ Spring Boot Learning 🐛 Hibernate Tables Not Creating — Debugging Story Everything looked correct… but: ❌ Tables were NOT getting created 🔍 Root Causes 👉 ddl-auto not set properly 👉 Old compiled files interfering 👉 Maven build not clean ✅ Fix ✔ Set in application.yml: spring: jpa: hibernate: ddl-auto: create ✔ Cleaned previous compiled files ✔ Reinstalled dependencies ✔ Rebuilt project 🔥 Result 👉 Tables created successfully 👉 JPA repositories detected 👉 Backend working as expected 🧠 The Shift 👉 Backend issues are often hidden in config 👉 Debugging > Coding (some days 😅) 👉 Real learning happens when things break 🔗 GitHub Repo: https://lnkd.in/gwHmAZaK 📈 Day 40 Progress: ✅ Learned rotation function optimization ✅ Fixed real Hibernate issue ✅ Improved debugging mindset 💬 What’s the most frustrating config bug you’ve faced? 👇 #100DaysOfCode #BackendDevelopment #SpringBoot #Java #LeetCode #Debugging #CodingJourney
To view or add a comment, sign in
-
-
While working on backend systems, I revisited some features from Java 17… and honestly, they make code much cleaner. One feature I find really useful is Records. 👉 Earlier: We used to write a lot of boilerplate just to create a simple data class. Getters Constructors toString(), equals(), hashCode() ✅ With Java 17 — Records: You can define a data class in one line: public record User(String name, int age) {} That’s it. Java automatically provides: ✔️ Constructor ✔️ Getters ✔️ equals() & hashCode() ✔️ toString() 💡 Practical usage: User user = new User("Dipesh", 25); System.out.println(user.name()); // Dipesh System.out.println(user.age()); // 25 🧠 Where this helps: DTOs in APIs Response objects Immutable data models What I like most is how it reduces boilerplate and keeps the code focused. Would love to know — are you using records in your projects? #Java #Java17 #Backend #SoftwareEngineering #Programming #Microservices #LearningInPublic
To view or add a comment, sign in
-
Was working on a Spring Boot REST API the other day. Everything looked fine entity class, repository, controller all set up. But two fields, createdAt and updatedAt, were coming back null in every response. Spent time checking the constructor, the DTO mapping, the database config. Turns out I just needed two annotations: @CreationTimestamp → auto-sets the time when record is created @UpdateTimestamp → auto-updates the time on every save Two lines. That's it. Hibernate handles everything behind the scenes you don't set these manually. One more thing I'd missed without @JsonFormat, Java's Timestamp serializes weirdly in JSON. Add this and it formats cleanly: @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") Small things. But they'll silently break your API if you miss them. #Java #SpringBoot #Backend #LearningInPublic #HibernateJPA
To view or add a comment, sign in
-
-
🚀 Day 2 of My Advanced Java Journey – JDBC Deep Dive Today, I explored deeper into JDBC, focusing on retrieving data, scrollable ResultSets, and metadata. 🔹 Retrieving Data from ResultSet JDBC provides multiple methods to fetch data from each column. We can retrieve data using: Column Index (int) Column Name (String) 👉 Common methods: getInt() getString() getFloat() getDouble() ✔️ Example concept: Using while(res.next()), we can iterate through rows and fetch values like id, name, designation, and salary. 🔹 Scrollable ResultSet (TYPE_SCROLL_SENSITIVE) Unlike normal ResultSets, scrollable ResultSets allow moving the cursor in multiple directions. 👉 Important methods: beforeFirst() afterLast() first() last() next() previous() absolute(int row) 💡 Helps in flexible data navigation. 🔹 ResultSet Metadata Metadata means data about data. Using ResultSetMetaData, we can get: Number of columns → getColumnCount() Column names → getColumnName(int column) Column types → getColumnType(int column) 🔍 What I explored beyond the session Difference between TYPE_FORWARD_ONLY, TYPE_SCROLL_INSENSITIVE, and TYPE_SCROLL_SENSITIVE Importance of CONCUR_READ_ONLY vs CONCUR_UPDATABLE Additional methods like getBoolean(), getDate(), getLong() Why column names are preferred over index (better readability & maintainability) 💡 Mastering ResultSet handling makes JDBC much more powerful for real-world backend applications. 🙌 Special thanks to the amazing trainers at TAP Academy: kshitij kenganavar Sharath R MD SADIQUE Bibek Singh Hemanth Reddy Vamsi yadav Harshit T Ravi Magadum Somanna M G Rohit Ravinder TAP Academy 📌 Learning in public. Growing every day. #Java #AdvancedJava #JDBC #BackendDevelopment #LearningInPublic #100DaysOfCode #VamsiLearns
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
Keep going, this is really helpful 👏