📄 Pagination in Spring Boot - Handle Large Data Efficiently Fetching all records at once = slow API + memory issues. Pagination solves this by loading data in chunks. ⚡ Why use Pagination? 🚀 Improves performance 💾 Reduces memory usage 📦 Handles large datasets easily 📊 Better user experience (page-wise data) 🧠 How it works (Spring Boot) Spring provides built-in support via Pageable. 👉 Controller @GetMapping("/users") public Page<User> getUsers(Pageable pageable) { return userService.getUsers(pageable); } 👉 Service Layer public Page<User> getUsers(Pageable pageable) { return userRepository.findAll(pageable); } 👉 Repository public interface UserRepository extends JpaRepository<User, Long> { } 👉 Request: /users?page=0&size=5&sort=name,asc 🔍 Using Custom Query @Query("SELECT u FROM User u WHERE u.active = true") Page<User> findActiveUsers(Pageable pageable); 🔄 Response Structure { "content": [...], "totalElements": 100, "totalPages": 20, "size": 5, "number": 0 } 🔁 Flow 1️⃣ Client sends page + size 2️⃣ Spring creates Pageable 3️⃣ Repository fetches limited data 4️⃣ Returns Page<T> with metadata 📌 Rule of Thumb Always use pagination for list APIs - never return full DB data in one call. 👉 If you are preparing for Java backend interviews, connect & follow - I share short, practical backend concepts regularly. #SpringBoot #Java #Backend #Pagination #RESTAPI #SoftwareEngineering
Tanmay Khilari’s Post
More Relevant Posts
-
Day 20. I stopped using `FetchType.EAGER`. Not because it’s wrong. Because it was silently killing my API. I used to write this: @OneToMany(fetch = FetchType.EAGER) private List<Order> orders; It worked. Until it didn’t. Every time I fetched a User, Hibernate also fetched ALL their orders. Didn’t matter if I needed them or not. One user → dozens of records 100 users → hundreds of queries Production → slow API That’s when it clicked. EAGER loading is convenient. But it’s expensive. And you don’t see the cost until it’s too late. So I changed it. (see implementation below 👇) @OneToMany(fetch = FetchType.LAZY) private List<Order> orders; Now data loads only when I ask for it. What I learned: → EAGER loads everything — even when you don’t need it → LAZY gives you control → Defaults are not always the right choice The hard truth: → Most developers use EAGER without thinking → It works fine in small data → It breaks under real load Using EAGER is easy. Controlling what your database loads is what makes you a backend developer. Are you still using `FetchType.EAGER`? 👇 Drop it below #SpringBoot #Java #Hibernate #BackendDevelopment #JavaDeveloper
To view or add a comment, sign in
-
-
#SpringUnpackedSeries - 03 Continuing from: https://lnkd.in/gJ4Wg6XN === HOW SPRING BOOT + JPA SIMPLIFY YOUR DATA LAYER? === Ever wonder how Spring Boot manages to connect to a database with almost zero manual setup? It’s all about the "Autopilot" mode! When you combine Spring Boot with JPA (Java Persistence API), the framework takes over the repetitive, "boring" parts of coding, allowing you to focus on building features rather than plumbing. --- The 3-Step Magic Trick --- • Step 1: The Input You provide the basics: a few dependencies in your build.gradle, simple properties, and your @Entity classes. That’s it! • Step 2: The Autopilot Spring Boot kicks in to scan your project. It finds your database drivers, initializes Hibernate, and automatically sets up the EntityManagerFactory. • Step 3: The Result The framework builds the "heavy" machinery. It generates SQL, manages transactions, and handles connection pooling without you writing a single line of JDBC code. --- Why This Matters? --- • Speed: Go from an empty project to a working database layer in minutes. • Clean Code: No more messy boilerplate or manual SQL management. • Efficiency: Let the framework handle complex tasks like Transaction Management and Data Access automatically. #SpringUnpacked #SpringBoot #Java #JPA #Hibernate #SoftwareDevelopment #CodingLife #BackendDevelopment #ProgrammingTips #TechCommunity #WebDevelopment
To view or add a comment, sign in
-
-
One small JPA setting… can silently destroy your application 𝗽𝗲𝗿𝗳𝗼𝗿𝗺𝗮𝗻𝗰𝗲. 𝗟𝗮𝘇𝘆 𝘃𝘀 𝗘𝗮𝗴𝗲𝗿 𝗹𝗼𝗮𝗱𝗶𝗻𝗴 Most developers don’t think about this at first. They just map entities and move on. But this one decision can make or break your performance. Let’s simplify it: You have two entities: User → Orders Now the question is: When you fetch a user… should orders be fetched too? 🔹 EAGER Loading “Load everything immediately” @𝗢𝗻𝗲𝗧𝗼𝗠𝗮𝗻𝘆(𝗳𝗲𝘁𝗰𝗵 = 𝗙𝗲𝘁𝗰𝗵𝗧𝘆𝗽𝗲.𝗘𝗔𝗚𝗘𝗥) User is loaded ✅ Orders are also loaded instantly ✅ Sounds good… but wait If a user has 1000 orders… you just fetched everything — even if you don’t need it. 🔹 LAZY Loading “Load only when needed” @𝗢𝗻𝗲𝗧𝗼𝗠𝗮𝗻𝘆(𝗳𝗲𝘁𝗰𝗵 = 𝗙𝗲𝘁𝗰𝗵𝗧𝘆𝗽𝗲.𝗟𝗔𝗭𝗬) User is loaded ✅ Orders are fetched only when accessed Much more efficient… right? But here’s where it gets interesting Lazy loading can cause 𝗡+𝟭 𝗾𝘂𝗲𝗿𝘆 𝗽𝗿𝗼𝗯𝗹𝗲𝗺 Example: Fetch 10 users Then access orders for each user Result: 1 query (users) + 10 queries (orders) = 11 queries. So what’s the right choice? It 𝗱𝗲𝗽𝗲𝗻𝗱𝘀. 🔹 Use LAZY when: You don’t always need related data You want better control over performance 🔹 Use EAGER when: Data is always required Relationship is small and predictable 💡 Real insight Performance issues in backend systems are rarely about “bad code”… They’re about invisible decisions like this. Next time your API slows down, don’t just check the query… Check how your data is being loaded. #SpringBoot #Java #BackendDevelopment #SoftwareEngineering #Spring #SpringFramework #JavaDevelopers #SpringAnnotations #JPA #Hibernate #RDBMS #Microservices #SystemDesign #aswintech
To view or add a comment, sign in
-
Deep Dive into Backend: Weather Forecast REST API with Spring Boot To strengthen my backend development skills, I recently built a Weather Forecast REST API using Spring Boot, with a focus on clean architecture and scalability. What’s under the hood: • Layered architecture (Controller → Service → Repository) • Data persistence using Spring Data JPA & Hibernate • Structured JSON responses with DTO mapping • Global exception handling for better API stability Why this project: Beyond simply fetching weather data, the goal was to apply industry-standard practices such as DTO patterns, proper request validation, and clean code structuring. Tech Stack: Java, Spring Boot, Spring Data JPA, Hibernate, H2/MySQL This project gave me a better understanding of how to design scalable and maintainable backend systems using Spring Boot. #SpringBoot #JavaDeveloper #BackendDevelopment #RESTAPI #JPA #Hibernate #SoftwareEngineering #LearningInPublic
To view or add a comment, sign in
-
Clean Architecture fixes this permanently. Here's the rule: dependencies point INWARD only. 📦 Domain layer (innermost) → Pure Java. Zero Spring. Zero DB. → This is where your business rules live. → If this layer compiles, your business logic is correct — regardless of framework. ⚙️ Application layer → @Service classes. Use cases. Orchestration. → Calls domain objects. Talks to repository interfaces. → Never talks directly to controllers or DB. 🔌 Infrastructure layer → @Repository implementations. JPA. External APIs. → The only layer that knows about Spring Data, Hibernate, or AWS. 🌐 Presentation layer → @RestController only. Maps HTTP to use cases. → Converts DTOs. Nothing more. The result? → You can swap your database without touching business logic → You can test domain rules without starting Spring → New teammates understand the codebase in hours, not days This is what I build. Every project. Every time. #CleanArchitecture #Java #SpringBoot #SoftwareDesign #BackendDeveloper #FullStackDeveloper
To view or add a comment, sign in
-
Your database is not the problem. Your queries are. A slow application doesn't always mean you need a bigger server or a fancier cache. Most of the time, the bottleneck is sitting right there in a query nobody questioned. Spring Boot, or ORMs in general makes data access so easy that it's tempting to just let JPA handle everything. And it will, until it won't. The classic traps: N+1 queries. You fetch a list of 100 orders. Then for each order, JPA quietly fires another query to get the customer. That's 101 queries instead of 1. Feels fine in dev with 10 rows. Falls apart in prod with 100,000. Fetching everything when you need one field. findById() returns the full entity when the screen only needs a name and a date. Multiply that by thousands of requests and you're moving data for no reason. No pagination. findAll() sounds harmless. Until your table hits 2 million rows and you just loaded all of them into memory. Ignoring indexes. A query that runs in 3ms on 1,000 rows runs in 4 seconds on 1,000,000 if the column isn't indexed. The code didn't change. The data did. Use @Query when the query matters. Use projections or DTOs to fetch only what you need. Add @EntityGraph to control fetching explicitly. Paginate by default. And always look at the actual SQL being generated. What Hibernate writes is not always what you'd write. Performance issues are rarely mysterious. They're usually a query doing too much, too often, or too blindly. Read your queries like they cost money. Because in production, they do ! #SpringBoot #Java #DatabasePerformance #BackendDevelopment #SoftwareEngineering #CleanCode #JPA #Hibernate #TechTips #WebDevelopment
To view or add a comment, sign in
-
-
🚀 Appify Prefab 0.6.5 is out! This release brings some massive quality-of-life improvements for Domain-Driven Design, documentation, and database mapping. Here is what’s new: 🔥 Major Features: - Unified Documentation: Annotate classes and fields with @Doc to automatically generate docs across OpenAPI, AsyncAPI, and Avro schemas. - Smart REST Parameters: You can now use @Aggregate annotated classes directly as parameters in REST requests—Prefab will automatically handle the ID lookup for you. - Streamlined Testing: Automatically generate Object Mothers for requests and events. - Polymorphic Aggregate Roots: Simplify your architecture with support for a single URL endpoint and a single database table for all subtypes. - Eventual Consistency Made Easy: Avoid two-phase commit (2PC) issues with @AsyncCommit. Publish events from REST requests and commit changes to the DB directly from your event handlers. 🛠️ Minor Features & Fixes: - Introduced @DbDocument to map specific parts of an aggregate root tree directly to JSONB. - Improved PostgreSQL mapping for deeply nested aggregate roots. Added support for the SQL TEXT type. - Improved the out-of-the-box developer experience: DB migrations and PostgreSQL Testcontainers are now enabled and configured by default! Check out the full release details here: https://lnkd.in/eTGvgb9y #SpringBoot #DDD #EDA #PostgreSQL #Java
To view or add a comment, sign in
-
Spring Data JDBC brings out the best in #Kotlin. Constructor-based mapping means val fields stay truly immutable – no no-arg constructors, no reflection tricks. Data classes work as aggregates, value classes map natively with no @Embedded or extra setup, and .copy() keeps updates clean. No proxies, no hidden state. Just Kotlin, working as intended. Check it out 👇 https://jb.gg/agfdv4
To view or add a comment, sign in
-
Understanding #SpringBoot Flow Architecture If you are diving into backend development with Java, understanding how data flows through a Spring Boot application is a game-changer. I found this great visual that simplifies the entire process. Here is a quick breakdown of how a request actually travels through the system: 1. The #Client (The Start) Everything begins with the Client (like a web browser or a mobile app) sending an HTTPS Request. This could be anything from logging in to fetching a list of products. 2. The #Controller (The Gatekeeper) The request first hits the Controller. Think of this as the front desk. It handles the incoming request, decides where it needs to go, and sends back the final response to the user. 3. The #Service Layer (The Brain) The Controller passes the job to the Service Layer. This is where the "magic" happens—all the business logic, calculations, and rules are kept here. Pro Tip: This layer uses Dependency Injection to pull in the Repository it needs to talk to the database. 4. The #Repository & Model (The Data Handlers) Repository: This class extends CRUD services, allowing the app to Create, Read, Update, or Delete data without writing complex SQL every time. Model: This represents the structure of your data (like a "User" or "Product" object). 5. #Database (The Memory) Finally, using JPA / Spring Data, the application communicates with the Database to store or retrieve the information requested by the client. #SpringBoot #Java #Spring #SpringSecurity #SystemDesign #Backend
To view or add a comment, sign in
-
-
What Is Spring + Temporal? Spring Boot + Temporal lets you run long‑running, fault‑tolerant workflows as code, with automatic retries, state persistence, and worker orchestration — all configured using Spring Boot auto‑configuration. 🚀 Why Use Temporal With Spring Boot? Temporal solves problems that are extremely hard with normal Spring apps: Long-running workflows (minutes → months) Automatic retries with backoff State persistence & deterministic replay Crash recovery without losing progress Event-driven orchestration Strong consistency guarantees Spring Boot integration adds: Auto-configured WorkflowClient Auto-discovery of Workflows & Activities Declarative worker configuration Easy switch between local server & Temporal Cloud ⚙️ How Spring Boot Integrates With Temporal 1️⃣ Add Dependency xml <dependency> <groupId>io.temporal</groupId> <artifactId>temporal-spring-boot-starter</artifactId> <version>1.31.0</version> </dependency> 2️⃣ Configure Connection (application.yml) yaml spring.temporal: connection: target: local # or host:port namespace: default This automatically creates a WorkflowClient bean. 3️⃣ Define a Workflow java @WorkflowInterface public interface OrderWorkflow { @WorkflowMethod String processOrder(String orderId); } 4️⃣ Implement the Workflow java public class OrderWorkflowImpl implements OrderWorkflow { private final PaymentActivities payment = Workflow.newActivityStub( PaymentActivities.class, ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofMinutes(2)).build() ); @Override public String processOrder(String orderId) { payment.charge(orderId); return "Order processed: " + orderId; } } 5️⃣ Implement Activities java public class PaymentActivitiesImpl implements PaymentActivities { @Override public void charge(String orderId) { System.out.println("Charging for order: " + orderId); } } 6️⃣ Start a Workflow From a Spring Controller java @RestController public class OrderController { @Autowired private WorkflowClient client; @PostMapping("/order/{id}") public String start(@PathVariable String id) { OrderWorkflow workflow = client.newWorkflowStub( OrderWorkflow.class, WorkflowOptions.newBuilder().setTaskQueue("ORDER_QUEUE").build() ); WorkflowClient.start(workflow::processOrder, id); return "Order started!"; } } This shows: Spring Boot triggers workflows Temporal Server orchestrates Workers execute workflow & activity code State is persisted automatically 📦 Features You Get Automatically Use Temporal when you need: Payment workflows Order processing Document approval Shipping orchestration Retry-heavy external API calls Human-in-the-loop workflows #SpringBoot #SpringSecurity #Java #BackendDevelopment #SoftwareEngineering #ApplicationSecurity #APISecurity #ProgrammingTips #DevelopersCommunity
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
Great reminder about implementing pagination in Spring Boot. Fetching large datasets in smaller chunks improves API responsiveness and gives users a smoother experience.