🛠️ Implementation: Pagination & Sorting in a Spring Boot API When working with large datasets, returning everything at once is not a good idea. It increases response time, impacts performance, and doesn’t scale well. --- 🔍 Problem My API was returning a huge dataset in a single response → leading to slow performance and inefficient data handling. --- 🛠️ Solution Implemented pagination along with basic sorting using Spring Boot. Adding the implementation below for reference 👇 ```java id="q7md2x" Pageable pageable = PageRequest.of(pageNumber, pageSize, Sort.by(sortBy).ascending()); Page<Product> page = productRepository.findAll(pageable); ``` --- 💡 What this improves ✔️ Breaks large data into manageable pages ✔️ Reduces response payload ✔️ Improves API performance ✔️ Supports field-based sorting (ascending order) --- 🔎 About sorting Sorting is applied based on a specific field (like name, price, or date). Currently, the API sorts results in ascending order, but this can be extended to support dynamic sorting (ASC/DESC) based on user input. This flexibility is important when building APIs that serve different frontend requirements. --- 🧠 Key takeaway Backend development is not just about returning data — it’s about returning it *efficiently and in a way that clients can control*. --- 📈 Real-world impact Pagination combined with sorting is essential for building scalable APIs, especially when handling large datasets in production systems. --- #SpringBoot #Java #BackendDevelopment #APIDesign #SoftwareEngineering #softwaredeveloper
Pagination & Sorting in Spring Boot API
More Relevant Posts
-
🛠️ 𝐈𝐦𝐩𝐥𝐞𝐦𝐞𝐧𝐭𝐚𝐭𝐢𝐨𝐧: 𝐏𝐚𝐠𝐢𝐧𝐚𝐭𝐢𝐨𝐧 & 𝐒𝐨𝐫𝐭𝐢𝐧𝐠 𝐢𝐧 𝐚 𝐒𝐩𝐫𝐢𝐧𝐠 𝐁𝐨𝐨𝐭 A𝐏𝐈 When working with large datasets, returning everything at once is never a good idea. It increases response time, impacts performance, and doesn’t scale well. 🔍 𝐏𝐫𝐨𝐛𝐥𝐞𝐦 My API was returning a huge dataset in a single response → leading to slow performance and inefficient data handling. 💡 𝐖𝐡𝐚𝐭 𝐭𝐡𝐢𝐬 𝐢𝐦𝐩𝐫𝐨𝐯𝐞𝐬 ✔️ Breaks large data into manageable pages ✔️ Reduces response payload ✔️ Improves API performance ✔️ Allows dynamic sorting ✔️ Supports field-based sorting ascending order 🧠 𝐊𝐞𝐲 𝐭𝐚𝐤𝐞𝐚𝐰𝐚𝐲 Backend development is not just about returning data it’s about returning it efficiently and responsibly. 📈 𝐑𝐞𝐚𝐥-𝐰𝐨𝐫𝐥𝐝 𝐢𝐦𝐩𝐚𝐜𝐭 Pagination combined with sorting is essential for building scalable APIs, especially when handling large datasets in production systems 🔽 Adding the implementation below for reference #SpringBoot #Java #BackendDevelopment #APIDesign #SoftwareEngineering
To view or add a comment, sign in
-
-
𝗦𝗽𝗿𝗶𝗻𝗴 𝗕𝗼𝗼𝘁 𝗔𝗿𝗰𝗵𝗶𝘁𝗲𝗰𝘁𝘂𝗿𝗲 – 𝗛𝗶𝗴𝗵 𝗹𝗲𝘃𝗲𝗹 𝗣𝗿𝗮𝗰𝘁𝗶𝗰𝗮𝗹 𝗕𝗿𝗲𝗮𝗸𝗱𝗼𝘄𝗻 When building scalable backend systems, having a clear architectural understanding of Spring Boot is a game changer. Here’s a simple yet powerful way to think about it 👇 𝗖𝗼𝗿𝗲 𝗟𝗮𝘆𝗲𝗿 (𝗙𝗼𝘂𝗻𝗱𝗮𝘁𝗶𝗼𝗻) This is where everything starts. • Auto-Configuration – Reduces boilerplate, smart defaults • Dependency Injection – Loose coupling, easier testing • Application Context – Heart of Spring, manages beans lifecycle 👉 This layer makes Spring Boot “plug & play” 𝗪𝗲𝗯 𝗟𝗮𝘆𝗲𝗿 (𝗘𝗻𝘁𝗿𝘆 𝗣𝗼𝗶𝗻𝘁) Handles all incoming traffic. • REST Controllers – Expose APIs • Request Mapping – Route requests effectively • Validation – Ensure clean & safe inputs 👉 This is where your APIs meet the world 𝗗𝗮𝘁𝗮 𝗟𝗮𝘆𝗲𝗿 (𝗣𝗲𝗿𝘀𝗶𝘀𝘁𝗲𝗻𝗰𝗲) Responsible for data handling. • Spring Data JPA – Abstracts DB interactions • Repositories – Clean data access layer • Transactions – Ensure consistency & reliability 👉 Focus: Integrity + performance 𝗦𝗲𝗰𝘂𝗿𝗶𝘁𝘆 𝗟𝗮𝘆𝗲𝗿 (𝗣𝗿𝗼𝘁𝗲𝗰𝘁𝗶𝗼𝗻) Because production ≠ demo apps. • JWT Authentication – Stateless & scalable • Role-Based Access Control (RBAC) – Fine-grained permissions 👉 Secure by design, not as an afterthought 𝗢𝗯𝘀𝗲𝗿𝘃𝗮𝗯𝗶𝗹𝗶𝘁𝘆 (𝗣𝗿𝗼𝗱𝘂𝗰𝘁𝗶𝗼𝗻 𝗥𝗲𝗮𝗱𝗶𝗻𝗲𝘀𝘀) What you don’t measure, you can’t improve. • Actuator – Health & metrics endpoints • Prometheus – Metrics collection • Grafana – Visualization & alerts 👉 This is where real engineering begins 𝙁𝙞𝙣𝙖𝙡 𝙏𝙝𝙤𝙪𝙜𝙝𝙩: A good Spring Boot application isn’t just about writing controllers — it’s about designing layers that are scalable, secure, and observable. #SpringBoot #Java #BackendDevelopment #Microservices #SystemDesign #SoftwareArchitecture #DevOps #Observability #JWT #SpringFramework #CodeQuality #TechLeadership #codefarm
To view or add a comment, sign in
-
-
As backend developers, we often deal with complex objects — multiple fields, optional parameters, and different configurations. Writing clean, maintainable, and scalable code in such scenarios can get tricky. That’s where the Builder Design Pattern shines. 💡 Instead of creating objects using large constructors or messy setters, the Builder pattern allows us to construct objects step-by-step — making the code more readable and flexible. 🔹 Why use Builder Pattern? Avoids telescoping constructor problem Improves code readability Handles optional parameters gracefully Encourages immutability Makes object creation more controlled and expressive 🔹 Where I find it useful (real backend scenarios): Creating complex DTOs or API request/response objects Building configuration objects (DB configs, service configs) Constructing domain models with many optional fields Writing test data builders for clean test cases 🔹 Quick Example : Instead of: new User("Aritra", "aritra@mail.com", "123", null, null, true); We write: User user = User.builder() .name("Aritra") .email("aritra@mail.com") .phone("123") .isActive(true) .build(); Much cleaner. Much safer. Much scalable. 💭 Key Insight: Builder pattern is not just about avoiding constructor chaos — it's about designing code that scales with complexity. If you're working in backend systems (especially with Java, Spring Boot, or microservices), mastering this pattern will level up your design skills significantly. Check it out - https://lnkd.in/gUmCUB_u #BackendDevelopment #Java #SystemDesign #DesignPatterns #CleanCode #SoftwareEngineering
To view or add a comment, sign in
-
-
Many developers know SOLID in theory. Far fewer know how to apply it in real backend systems. In projects, SOLID is not about memorizing principles. It is about writing code that survives change, scales with the business, and stays maintainable over time. Here is how SOLID appears in real backend development: - S - Single Responsibility Principle A class should have one reason to change. Bad example: UserService handles validation, persistence, email, and report generation. Better approach: - UserService = business rules - UserRepository = database access - EmailService = notifications - ReportService = exports Result: cleaner code and easier testing. - O - Open/Closed Principle Open for extension, closed for modification. Instead of editing the same payment class every time a new method appears: Use interfaces: PaymentProcessor - CreditCardProcessor - PixProcessor - PayPalProcessor Now you add new processors without breaking old code. - L - Liskov Substitution Principle Subclasses must behave like their parent types. If PremiumAccount extends Account, it should work anywhere Account is expected. If it throws unsupported exceptions or changes core behavior, inheritance was the wrong choice. Use composition when behavior differs too much. - I - Interface Segregation Principle Clients should not depend on methods they do not use. Bad: Worker { code(); deploy(); manageBudget(); hire(); } Better: - Developer - Deployer - Manager Small focused interfaces reduce coupling. - D - Dependency Inversion Principle Depend on abstractions, not implementations. Instead of: OrderService -> MySQLRepository Use: OrderService -> OrderRepository Then you can swap MySQL, PostgreSQL, MongoDB, or mocks for tests. Why this matters in backend systems: - Faster unit tests - Easier refactoring - Cleaner architecture - Lower maintenance cost - Better scalability for teams and codebases SOLID is not about making code complex. It is about making change less painful. Good backend systems are not built only to run today. They are built to evolve tomorrow. Which SOLID principle do you see being violated most often in enterprise projects? #Java #Backend #SOLID #CleanCode #SoftwareArchitecture #SpringBoot #Programming #Developers #TechLeadership #Coding #SystemDesign #Microservices #Engineering #JavaDeveloper #BestPractices
To view or add a comment, sign in
-
-
🏗️ Spring Boot Project Structure — What Actually Scales in Real Projects When working on Spring Boot applications, project structure may seem simple at the beginning. But as the project grows, a poor structure quickly turns into hard-to-maintain and messy code 😅 Over time, adopting a clean and structured approach makes a huge difference 👇 🔹 1. Controller Layer Handles API requests & responses — keep it thin, no business logic. 🔹 2. Service Layer (Interface) Defines business operations → improves flexibility & testability. 🔹 3. Service Implementation Contains core business logic → easy to modify without affecting other layers. 🔹 4. Repository Layer Handles DB operations using JPA → clean separation of persistence logic. 🔹 5. Entity Layer Represents database tables → avoid exposing entities directly in APIs. 🔹 6. DTO Layer Used for request/response → better control over API contracts. 🔹 7. Mapper Layer Converts Entity ↔ DTO → avoids repetitive code in services. 🔹 8. Configuration Layer Centralized configs (Security, CORS, Swagger, etc.). 🔹 9. Global Exception Handling Use @ControllerAdvice for consistent error responses. 🔹 10. Utility / Common Layer Reusable helpers (constants, validators, utilities). 🚀 What Changed Everything? Initially, a layer-based structure worked fine. But as the application scaled, switching to a feature-based structure (e.g., user/, payment/, expense/) made it: ✔ Easier to scale ✔ Easier to debug ✔ Easier to maintain 💡 Key Takeaways ✔ A clean structure saves time in the long run ✔ Keep layers loosely coupled ✔ Don’t mix responsibilities 👉 Good architecture isn’t overengineering — it’s future-proofing your codebase. #SpringBoot #Java #BackendDevelopment #SoftwareArchitecture #CleanCode
To view or add a comment, sign in
-
-
🚀 Are your APIs ready for the future… or just working for today? Building APIs is easy. But building APIs that scale, evolve, and remain backward compatible — that’s where real engineering begins. This visual breaks down two critical concepts every backend developer must master: 🔹 API Versioning As your application grows, your APIs change. But breaking existing clients? ❌ Not acceptable. 👉 Versioning helps you: ✔ Maintain backward compatibility ✔ Introduce new features safely ✔ Support multiple client versions 💡 Common strategies: URI Versioning → /api/v1/users Request Parameter → ?version=1 Header Versioning → X-API-VERSION Content Negotiation ⏱️ Time-Stamping (Auditing) Ever wondered how systems track when data was created or updated? 👉 With Spring Boot: ✔ @CreationTimestamp → Auto set when record is created ✔ @UpdateTimestamp → Auto update on modification No manual tracking needed — Spring + JPA handles it for you. 🔄 How It All Connects Client → Versioned API → Controllers (v1, v2) → Database Result? ✔ Smooth API evolution ✔ Better debugging & auditing ✔ Clean and maintainable architecture 🔥 Key Insight: Good APIs don’t just work — they evolve gracefully without breaking users. 💬 Question for Developers: Which versioning strategy do you prefer in real projects — URI or Header-based? #SpringBoot #Java #BackendDevelopment #APIDesign #SoftwareEngineering #Microservices #LearningInPublic #Developers #CodingJourney
To view or add a comment, sign in
-
-
Everyone is building fast with Spring Boot… but silently killing their architecture with one keyword 👇 👉 `new` Looks harmless right? But this one line can destroy **scalability, testability, and flexibility**. --- ## ⚠️ Real Problem You write this: ```java @Service public class OrderService { private PaymentService paymentService = new PaymentService(); // ❌ } ``` Works fine. No errors. Ship it 🚀 But now ask yourself: * Can I mock this in testing? ❌ * Can I switch implementation easily? ❌ * Is Spring managing this object? ❌ You just bypassed **Dependency Injection** completely. --- ## 💥 What actually went wrong? You created **tight coupling**. Now your code is: * Hard to test * Hard to extend * Painful to maintain --- ## ✅ Correct Way (Production Mindset) ```java @Service public class OrderService { private final PaymentService paymentService; public OrderService(PaymentService paymentService) { this.paymentService = paymentService; } } ``` Now: ✔ Loose coupling ✔ Easy mocking ✔ Fully Spring-managed lifecycle --- ## 🚨 Sneaky Mistake (Most devs miss this) ```java public void process() { PaymentService ps = new PaymentService(); // ❌ hidden violation } ``` Even inside methods — it’s still breaking DI. --- ## 🧠 Where `new` is ACTUALLY OK ✔ DTO / POJO ✔ Utility classes ✔ Builders / Factory pattern --- ## ❌ Where it’s NOT OK ✖ Services ✖ Repositories ✖ External API clients ✖ Anything with business logic --- ## ⚡ Reality Check In the AI era, anyone can generate working code. But production-ready engineers ask: 👉 “Who is managing this object?” 👉 “Can I replace this tomorrow?” 👉 “Can I test this in isolation?” --- ## 🔥 One Line to Remember > If you are using `new` inside a Spring-managed class… > you are probably breaking Dependency Injection. --- Stop writing code that just works. Start writing code that survives. #Java #SpringBoot #CleanCode #SystemDesign #Backend #SoftwareEngineering
To view or add a comment, sign in
-
In a Spring Boot application, code is structured into layers to keep things clean, maintainable, and scalable. The most common layers are Controller, Service, and Repository each with a clear responsibility. i)Controller * Entry point of the application. * Handles incoming HTTP requests (GET, POST, etc.). * Accepts request data (usually via DTOs). * Returns response to the client. ii)Service * Contains business logic. * Processes and validates data. * Converts DTO ↔ Entity. iii)Repository * Connects with the database. * Performs CRUD operations. * Works directly with Entity objects. Request Flow (Step-by-Step): Let’s understand what happens when a user sends a request: 1. Client sends request Example: `POST /users` with JSON data. 2. Controller receives request * Maps request to a method. * Accepts data in a DTO. ``` @PostMapping("/users") public UserDTO createUser(@RequestBody UserDTO userDTO) { return userService.createUser(userDTO); } ``` 3. Controller → Service * Passes DTO to Service layer. 4. Service processes data * Applies business logic. * Converts DTO → Entity. ``` User user = new User(); user.setName(userDTO.getName()); ``` 5. Service → Repository * Calls repository to save data. ``` userRepository.save(user); ``` 6. Repository → Database * Data is stored in DB. 7. Response Flow Back * Repository → Service → Controller. * Entity converted back to DTO. * Response sent to client. Why DTO is Used: * Prevents exposing internal entity structure. * Controls input/output data. * Improves security. * Keeps layers independent. Why This Architecture Matters: * Clear separation of concerns * Easier debugging & testing * Scalable and maintainable codebase #Java #Spring #SpringBoot #BackendDevelopment #SoftwareEngineering #JavaDeveloper
To view or add a comment, sign in
-
-
I hit a strange realization today. Not a new concept. Not a new framework. Just something I’ve already used in production. But still… *I couldn’t explain it cleanly. We often say “I know this.” But do we really? Today’s trigger was a simple API design scenario in Spring Framework: 👉 Upload a file + send structured JSON data in the same request Sounds basic, right? But when I tried to break it down clearly— the *why*, the *how*, the *right annotation*— there was hesitation. --- Then the clarity came back: * `@RequestParam` → key-value inputs * `@PathVariable` → resource identity * `@RequestBody` → pure JSON payload * `@RequestPart` → **multipart boundary where file + structured data meet That moment reminded me of something deeper: > “Exposure creates familiarity. > But only articulation proves understanding.” In real systems, this gap shows up everywhere: * You’ve seen the pattern, but can’t justify it * You’ve fixed the bug, but can’t explain root cause * You’ve used the annotation, but don’t know *why it exists* At scale, this matters. Because senior engineering is not about: ❌ Writing more code It’s about: ✔ Explaining decisions clearly ✔ Designing with intent ✔ Debugging with first-principles thinkin --- **Today wasn’t about learning something new. It was about realizing what I hadn’t fully understood.** And that’s a different kind of progress. #SoftwareEngineering #Java #SpringBoot #SystemDesign #Backend #EngineeringMindset
To view or add a comment, sign in
Explore related topics
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