🚀 DAY 16 — @PathVariable, @RequestParam, @RequestBody ✅ 1. CLEAR CONCEPT (VERY IMPORTANT) 👉 These 3 are used to get data from client AnnotationFrom where data comes@PathVariableURL path@RequestParamQuery parameter@RequestBodyRequest body (JSON) 🧠 SIMPLE UNDERSTANDING 👉 3 ways client sends data: URL → /users/1 → PathVariable Query → /users?id=1 → RequestParam Body → JSON → RequestBody 💻 EXAMPLES (VERY IMPORTANT) 🔹 1. @PathVariable @GetMapping("/users/{id}") public String getUser(@PathVariable int id) { return "User id: " + id; } 👉 URL: /users/1 🔹 2. @RequestParam @GetMapping("/users") public String getUser(@RequestParam int id) { return "User id: " + id; } 👉 URL: /users?id=1 🔹 3. @RequestBody @PostMapping("/users") public String addUser(@RequestBody String name) { return "User " + name + " added"; } 👉 Body (JSON): { "name": "Ashish" } 🔄 FLOW (IMPORTANT) 👉 Client → sends data → Controller receives → Method executes 🎯 INTERVIEW QUESTIONS (MUST 🔥) ❓ Difference: @PathVariable vs @RequestParam? 👉 PathVariable → part of URL 👉 RequestParam → query parameter ❓ What is @RequestBody? 👉 Takes JSON data from client ❓ When to use @PathVariable? 👉 When ID is part of URL ❓ When to use @RequestParam? 👉 For optional/filter values ⚡ BEST PRACTICES ✔ Use PathVariable for IDs ✔ Use RequestParam for filters/search ✔ Use RequestBody for POST/PUT 💡 FINAL UNDERSTANDING 👉 Path → URL data 👉 Param → Query data 👉 Body → JSON data 💬 Which one confused you — Path or Param? Day 16 done ✅ #SpringBoot #Java #BackendDevelopment #LearningInPublic #30DaysOfCode #Developers
Understanding @PathVariable, @RequestParam, @RequestBody in Spring Boot
More Relevant Posts
-
🚀 DAY 15 — Build REST APIs (GET, POST, PUT, DELETE) ✅ 1. CLEAR CONCEPT (VERY IMPORTANT) 👉 API = way for client to communicate with server 👉 REST APIs use HTTP methods 🌐 HTTP METHODS (CORE 🔥) MethodUseGETFetch dataPOSTCreate dataPUTUpdate dataDELETEDelete data 💻 FULL EXAMPLE (VERY IMPORTANT) @RestController @RequestMapping("/users") public class UserController { // GET → fetch users @GetMapping public List<String> getUsers() { return List.of("Ashish", "Rahul"); } // POST → add user @PostMapping public String addUser(@RequestBody String name) { return "User " + name + " added"; } // PUT → update user @PutMapping("/{id}") public String updateUser(@PathVariable int id, @RequestBody String name) { return "User " + id + " updated to " + name; } // DELETE → delete user @DeleteMapping("/{id}") public String deleteUser(@PathVariable int id) { return "User " + id + " deleted"; } } 🔄 FLOW (IMPORTANT) 👉 Client (Postman / Browser) → Controller → Method executes → Response returns 📌 API EXAMPLES GET → /users POST → /users PUT → /users/1 DELETE → /users/1 🎯 INTERVIEW QUESTIONS (MUST 🔥) ❓ What is REST API? 👉 Communication between client and server using HTTP ❓ Difference: GET vs POST? 👉 GET → fetch data 👉 POST → create data ❓ Difference: PUT vs PATCH? 👉 PUT → full update 👉 PATCH → partial update ❓ What is @RequestBody? 👉 Takes data from client ❓ What is @PathVariable? 👉 Gets value from URL ⚡ BEST PRACTICES (IMPORTANT) ✔ Use proper HTTP methods ✔ Use meaningful URLs (/users) ✔ Return proper responses ✔ Keep controller clean 💡 FINAL UNDERSTANDING 👉 GET → Read 👉 POST → Create 👉 PUT → Update 👉 DELETE → Remove 💬 Did you test APIs using Postman? Day 15 done ✅ #SpringBoot #Java #BackendDevelopment #LearningInPublic #30DaysOfCode #Developers
To view or add a comment, sign in
-
-
🚀 DSL vs @Query in Spring Data JPA While working with Spring Data JPA, I learned that by default it provides methods to work with the primary key like findById(). But what if we want to fetch data using other fields like name, age, etc.? 🤔 We have two approaches 👇 🔹 1. Domain-Specific Language (DSL) List<User> findByName(String name); ✔️ Method Naming Convention ✔️ Query is automatically generated ✔️ Easy to write and read ✔️ Best for simple queries 🔹 2. @Query Annotation @Query("SELECT u FROM User u WHERE u.name = :name") List<User> getUserByName(String name); ✔️ Query is written manually (JPQL/SQL) ✔️ More flexibility ✔️ Best for complex queries (joins, multiple conditions) 💡 Key Difference: DSL → Simple & automatic @Query → Flexible & customizable 🎯 Conclusion: Use DSL for quick and simple queries, and switch to @Query when you need more control. #Java #SpringBoot #SpringDataJPA #BackendDevelopment #Coding #Developers #Learning
To view or add a comment, sign in
-
-
💡 **Settlement Report Revamp** In today’s requirement, I was asked to redesign the format of a settlement report. The existing format was outdated and didn’t align with the latest UI/UX standards. Interestingly, I had worked on a similar requirement in my previous organization. Back then, we used a simple CSV format for reports. Most of the reports were generated directly from the database using MySQL stored procedures with the `OUTFILE` option. This approach was efficient for handling large datasets and ensured faster file generation. For this new requirement, however, the expectation was a more refined and presentable format. So, I used Java’s Apache POI library to generate the report (Excel/PDF-style formatting). Apache POI provides great flexibility in customizing layouts, styles, and structure, making it suitable for modern reporting needs. 🔍 **Key Learning / Thought:** While using Java (like Apache POI) gives more control over formatting and presentation, generating large reports directly from the database can still be more efficient in terms of performance. Iterating over large datasets in application code and then generating files can be resource-intensive. 👉 So the choice depends on the use case: * **Use DB-level generation** (e.g., CSV via stored procedures) for performance-heavy, large datasets * **Use application-level tools** (e.g., Apache POI) when formatting, styling, and customization are important Would love to hear how others approach report generation in their projects! #Java #SpringBoot #BackendDevelopment #SoftwareEngineering #LearningInPublic
To view or add a comment, sign in
-
Ever tried building a “global filter API” by joining multiple datasets into a single response? Sounds simple… until it isn’t. Recently, I worked on combining data from multiple sources into one API using native SQL joins. On paper, it looked efficient — one query, one response. Reality was different. ⚠️ Challenges I faced: LEFT JOIN created duplicate and bloated rows SELECT * caused column order mismatches during DTO mapping Handling array fields from DB to Java was tricky Inconsistent data types across sources (BigDecimal vs Double, Timestamp vs LocalDateTime) Trying to map everything into a single DTO led to tight coupling The biggest pain: splitting combined query results back into meaningful structures 💡 Key learnings: Avoid SELECT * in complex joins — always map explicitly Native queries + DTO mapping = order matters more than you think One “global” response is not always a good design Sometimes, separate APIs or structured responses are cleaner and scalable Debugging mapping issues can take more time than writing the query itself In the end, what seemed like a query problem turned out to be a design problem. How do you handle multi-source joins in your APIs? 🤔 #Java #SpringBoot #BackendDevelopment #SQL #DatabaseDesign #APIDesign #Microservices #SoftwareEngineering #CodingChallenges #Developers #TechLearning #CleanCode
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 14. My API worked perfectly. Until it hit 100 users. I had this: List<Order> orders = orderRepository.findAll(); for (Order order : orders) { System.out.println(order.getUser().getName()); } Because of queries I didn’t even know existed. Looks clean. It’s not. Here’s what was actually happening: → 1 query to fetch all orders → 1 query per order to fetch the user → 100 orders = 101 queries hitting your database That’s the N+1 problem. And it hides in plain sight. Your code looks clean. Your database is suffering. And you probably have this in your codebase right now. The fix is simple: Fetch what you need. In one query. @Query("SELECT o FROM Order o JOIN FETCH o.user") List<Order> findAllWithUser(); One query. One JOIN. Everything loaded together. What actually changes: → Performance — 101 queries becomes 1 → Scalability — works at 100 rows, breaks at 100,000 → Visibility — you won’t notice until production The hard truth: → ORMs make it easy to write slow code → Lazy loading is convenient until it isn’t → You need to know what SQL your code is generating Writing code that works is easy. Writing code that doesn’t silently destroy your database is the real skill. Are you logging your SQL queries in development? If not — you should be. 👇 Drop it below #SpringBoot #Java #Hibernate #BackendDevelopment #JavaDeveloper
To view or add a comment, sign in
-
#Post5 In the previous post, we saw how @RequestBody helps us handle request data. Now the next question is 👇 How do we get data from the URL? There are two common ways: • @PathVariable • @RequestParam Let’s understand 👇 👉 @PathVariable Used when the value is part of the URL path Example: GET /users/10 @GetMapping("/users/{id}") public String getUser(@PathVariable int id) { return "User id: " + id; } 👉 @RequestParam Used when the value comes as a query parameter Example: GET /users?id=10 @GetMapping("/users") public String getUser(@RequestParam int id) { return "User id: " + id; } 💡 Key difference: @PathVariable → part of URL @RequestParam → query parameter Key takeaway: Use the right approach based on how data is passed in the request 👍 In the next post, we will explore exception handling in Spring Boot 🔥 #Java #SpringBoot #BackendDevelopment #RESTAPI #LearnInPublic
To view or add a comment, sign in
-
The N+1 Query Problem — A Silent Performance Killer In one of my recent backend discussions, we revisited a classic issue that often goes unnoticed during development but can severely impact performance in production — the N+1 Query Problem. What is the N+1 Problem? It occurs when your application executes: 1 query to fetch a list of records (N items) Then executes N additional queries to fetch related data for each record Total = 1 + N queries Example Scenario: You fetch a list of 100 users, and for each user, you fetch their orders separately. That results in 101 database queries instead of just 1 or 2 optimized queries. Why is it Dangerous? 1. Increased database load 2. Slower response time 3. Poor scalability under high traffic 4. Hard to detect in small datasets, but disastrous at scale How to Overcome It? 1. Use Join Fetch (Eager Loading) Fetch related entities in a single query using JOINs. 2. Batch Fetching Load related data in chunks instead of one-by-one queries. 3. Entity Graphs (JPA) Define what relationships should be fetched together dynamically. 4. Use DTO Projections Fetch only required fields instead of entire objects. 5. Caching Strategy Leverage second-level cache to reduce repeated DB hits. 6. Monitor SQL Logs Always keep an eye on generated queries during development. Pro Tip: The N+1 problem is not a bug — it’s a design inefficiency. It often comes from default lazy loading behavior in ORMs like Hibernate. Interview Insight: A good engineer doesn’t just make code work — they make it scale efficiently. #Java #SpringBoot #Hibernate #BackendDevelopment #PerformanceOptimization #Microservices #InterviewPrep
To view or add a comment, sign in
-
Ever felt like SQL is doing more work than your actual logic? Writing queries… mapping results… handling connections… It gets repetitive really fast. What if you could just work with objects instead? That’s where 𝗢𝗥𝗠 (𝗢𝗯𝗷𝗲𝗰𝘁 𝗥𝗲𝗹𝗮𝘁𝗶𝗼𝗻𝗮𝗹 𝗠𝗮𝗽𝗽𝗶𝗻𝗴) comes in. Instead of writing complex SQL queries, you interact with your database using Java objects. No more manually converting 𝗿𝗼𝘄𝘀 → 𝗼𝗯𝗷𝗲𝗰𝘁𝘀. ORM does it for you. Let’s simplify it Without ORM: • Write SQL queries • Execute them • Map ResultSet to objects manually With ORM: • Create a class • Map it to a table • Call methods like save(), findById() That’s it. Popular ORM frameworks we might know: 𝗛𝗶𝗯𝗲𝗿𝗻𝗮𝘁𝗲 (most widely used) 𝗝𝗣𝗔 (Java Persistence API – standard) Why developers love ORM: • Faster development (less boilerplate) • Focus on business logic, not SQL • Automatic mapping between objects & tables • Easy integration with Spring Boot But here’s the real insight ORM is powerful… but blindly using it can hurt performance. Sometimes, writing a custom query is still the better choice. So the goal isn’t to avoid SQL… It’s to use 𝗢𝗥𝗠 𝘀𝗺𝗮𝗿𝘁𝗹𝘆. Next time you call 𝘀𝗮𝘃𝗲() in your project, remember — there’s a lot happening behind the scenes. #CoreJava #JavaDeveloper #Spring #Framework #ORM #SpringBoot #SpringData #Hibernate #SoftwareDevelopment #SQL #BackEndDevelopment #MicroServices #Programming #aswintech #Database #BuildBetter
To view or add a comment, sign in
-
When I first started with Spring Data JPA, this honestly felt like magic User findByEmail(String email); No SQL . No implementation. No query. And somehow… it worked. I used it for a long time before asking How is this actually possible? When I started with Spring Boot, I assumed this was just framework magic and I think many of us have felt the same. But that skips the most interesting part. It is not magic. It is a parser. Spring treats this method name: findByEmail() as a mini query language. Yes — the method name itself. Internally, Spring Data uses a parser called PartTree to read it. It breaks it into meaning like - * find → create a select query * By → start parsing criteria * Email → match an entity property If your entity has - private String email; Spring can derive a query from the method name.That is called query derivation using naming conventions.And this is where it gets deeper.Spring does not directly generate SQL.It first derives JPQL.Then Hibernate converts JPQL into database-specific SQL. This getSomeUserStuff() does not work. Because the parser does not understand it. But this findByEmailAndStatus() works because it follows a grammar.That is not just convention. That is a contract. And one detail many of use miss - Spring validates these derived queries at startup. Not later. So if you write: findByEmailAddress() but your entity does not have - emailAddress , your application can fail fast during startup. That is intentional framework design. Sometimes the most elegant engineering is hiding inside the APIs we use every day. #SpringBoot #Java #JPA #Hibernate #BackendDevelopment
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