<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Rushikesh Anil Varkale  on Medium]]></title>
        <description><![CDATA[Stories by Rushikesh Anil Varkale  on Medium]]></description>
        <link>https://medium.com/@varkalerushikesh?source=rss-ea54b0b43ef2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*KE2zt2XlAMVyG0yo</url>
            <title>Stories by Rushikesh Anil Varkale  on Medium</title>
            <link>https://medium.com/@varkalerushikesh?source=rss-ea54b0b43ef2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 11:14:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@varkalerushikesh/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Spring Data JPA Pagination & Sorting: Understanding PageRequest and Sort]]></title>
            <link>https://medium.com/@varkalerushikesh/spring-data-jpa-pagination-sorting-understanding-pagerequest-and-sort-68e4a529e9be?source=rss-ea54b0b43ef2------2</link>
            <guid isPermaLink="false">https://medium.com/p/68e4a529e9be</guid>
            <category><![CDATA[pagination]]></category>
            <category><![CDATA[sorting]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[jparepository]]></category>
            <dc:creator><![CDATA[Rushikesh Anil Varkale ]]></dc:creator>
            <pubDate>Fri, 28 Aug 2026 10:39:46 GMT</pubDate>
            <atom:updated>2026-08-28T10:39:46.270Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction to PageRequest</h3><p>When working with pagination in Spring Data JPA, we need to create a Pageable object that defines <strong>which page to retrieve, how many records to retrieve, and how the data should be sorted</strong>. PageRequest is commonly used for this purpose.</p><h4>What is PageRequest?</h4><p>PageRequest is a <strong>class in Spring Data</strong> that provides a convenient way to create Pageable objects for pagination and sorting.</p><h4>Where is PageRequest present?</h4><p>PageRequest is present in the:</p><pre>org.springframework.data.domain</pre><p>package.</p><p>It can be imported using:</p><pre>import org.springframework.data.domain.PageRequest;</pre><h4>Definition</h4><blockquote><strong><em>PageRequest is a class used to create </em></strong><strong><em>Pageable objects that define pagination and sorting information for database queries.</em></strong></blockquote><p>For example:</p><pre>Pageable pageable = PageRequest.of(0, 10);</pre><p>Here:</p><pre>Page Number → 0 (first page)<br>Page Size   → 10 records</pre><p>PageRequest is a concrete class that implements the Pageable interface.</p><p>The basic relationship is:</p><pre>PageRequest<br>     ↓<br>implements<br>     ↓<br>Pageable<br>     ↓<br>used by Repository<br>     ↓<br>returns Page&lt;T&gt;</pre><p>So, PageRequest is one of the most commonly used ways to create a Pageable object in Spring Data JPA.</p><h3>1. of(int page, int size) ⭐</h3><p>The of(int page, int size) method is used to <strong>create a </strong><strong>PageRequest object by specifying the page number and the number of records required per page</strong>.</p><p>It is the most commonly used method for creating a basic PageRequest.</p><h4>Method Signature</h4><pre>static PageRequest of(int page, int size);</pre><h4>Return Type</h4><pre>PageRequest</pre><p>Returns a PageRequest object containing the specified <strong>page number and page size</strong>.</p><h4>Parameters</h4><p>int page-The <strong>zero-based page number</strong> to request.</p><p>int size-The <strong>number of records required per page</strong>.</p><h4>Important Points</h4><ul><li>Page numbering starts from <strong>0</strong>.</li><li>page = 0 represents the first page.</li><li>size represents the maximum number of records requested per page.</li><li>Both page and size must be valid values:</li><li>page cannot be negative.</li><li>size must be greater than 0.</li><li>The returned PageRequest can be assigned to a Pageable reference because PageRequest implements Pageable.</li><li>No sorting is applied when using this overloaded method.</li></ul><h4>Example</h4><p>Suppose we want to retrieve the <strong>first page with 5 employees per page</strong>:</p><pre>Pageable pageable = PageRequest.of(0, 5);<br>Page&lt;Employee&gt; employeePage =<br>        employeeRepository.findAll(pageable);</pre><p>Here:</p><pre>Page Number → 0<br>Page Size   → 5</pre><p>We can also create a PageRequest directly:</p><pre>PageRequest pageRequest = PageRequest.of(2, 5);<br>System.out.println(pageRequest.getPageNumber());<br>System.out.println(pageRequest.getPageSize());</pre><p><strong>Output:</strong></p><pre>2<br>5</pre><p>So, <strong>of(int page, int size) creates a </strong><strong>PageRequest for the specified page number and page size.</strong></p><h3>2. of(int page, int size, Sort sort) ⭐</h3><p>The of(int page, int size, Sort sort) method is used to <strong>create a </strong><strong>PageRequest with a page number, page size, and sorting information</strong>.</p><p>It is useful when we want to <strong>apply pagination and sorting together</strong> in a database query.</p><h4>Method Signature</h4><pre>static PageRequest of(int page, int size, Sort sort);</pre><h4>Return Type</h4><pre>PageRequest</pre><p>Returns a PageRequest object containing the specified <strong>pagination and sorting information</strong>.</p><h4>Parameters</h4><p>int page:-The <strong>zero-based page number</strong> to request.</p><p>int sizeThe number of records required per page.</p><p>Sort sortThe sorting information to apply to the result.</p><h4>Important Points</h4><ul><li>Page numbering starts from <strong>0</strong>.</li><li>size specifies the number of records requested per page.</li><li>Sort specifies:</li></ul><pre>Which property to sort by.<br>Sorting direction (ASC or DESC).</pre><ul><li>The Sort object can contain <strong>one or multiple properties</strong>.</li><li>page cannot be negative.</li><li>size must be greater than 0.</li><li>The returned PageRequest can be assigned to a Pageable reference because PageRequest implements Pageable.</li></ul><h4>Example</h4><p>Suppose we want to retrieve <strong>page 0</strong>, with <strong>5 employees per page</strong>, sorted by salary in descending order:</p><pre>Pageable pageable = PageRequest.of(<br>        0,<br>        5,<br>        Sort.by(&quot;salary&quot;).descending()<br>);<br><br>Page&lt;Employee&gt; employeePage =<br>        employeeRepository.findAll(pageable);</pre><p>Here:</p><pre>Page Number → 0<br>Page Size   → 5<br>Sort        → salary DESC</pre><p>The result will contain up to <strong>5 employees</strong>, ordered by salary from highest to lowest.</p><p>We can also sort by multiple properties:</p><pre>Pageable pageable = PageRequest.of(<br>        0,<br>        5,<br>        Sort.by(&quot;department&quot;).ascending()<br>             .and(Sort.by(&quot;salary&quot;).descending())<br>);</pre><p>Here, employees are first sorted by <strong>department in ascending order</strong>, and employees within the same department are sorted by <strong>salary in descending order</strong>.</p><p>So, <strong>of(int page, int size, Sort sort) creates a </strong><strong>PageRequest with pagination and sorting information.</strong></p><h3>3. of(int page, int size, Sort.Direction direction, String... properties) ⭐</h3><p>The of(int page, int size, Sort.Direction direction, String... properties) method is used to <strong>create a </strong><strong>PageRequest with a page number, page size, sorting direction, and one or more properties to sort by</strong>.</p><p>It is useful when we want to <strong>apply pagination and sorting directly without creating a separate </strong><strong>Sort object</strong>.</p><h4>Method Signature</h4><pre>static PageRequest of(<br>        int page,<br>        int size,<br>        Sort.Direction direction,<br>        String... properties<br>);</pre><h4>Return Type</h4><pre>PageRequest</pre><p>Returns a PageRequest containing the specified <strong>pagination and sorting information</strong>.</p><h4>Parameters</h4><p><strong>int page </strong>— The zero-based page number to request.<br><strong>int size </strong>— The number of records required per page.<br><strong>Sort.Direction direction</strong> — The sorting direction: ASC or DESC.<br><strong>String… properties — </strong>One or more entity properties/fields by which the result should be sorted.</p><h4>Important Points</h4><ul><li>Page numbering starts from <strong>0</strong>.</li><li>size specifies the number of records requested per page.</li><li>direction specifies whether sorting should be:</li><li>Sort.Direction.ASC</li><li>Sort.Direction.DESC</li><li>properties is a <strong>varargs parameter</strong>, so we can provide one or multiple properties.</li><li>We don’t need to create a separate Sort object.</li><li>page cannot be negative.</li><li>size must be greater than 0.</li></ul><h4>Example</h4><p>Suppose we want to retrieve <strong>page 0</strong>, with <strong>5 employees per page</strong>, sorted by salary in descending order:</p><pre>Pageable pageable = PageRequest.of(<br>        0,<br>        5,<br>        Sort.Direction.DESC,<br>        &quot;salary&quot;<br>);<br><br>Page&lt;Employee&gt; employeePage =<br>        employeeRepository.findAll(pageable);</pre><p>Here:</p><pre>Page Number → 0<br>Page Size   → 5<br>Direction   → DESC<br>Property    → salary</pre><p>The result will contain up to <strong>5 employees</strong>, ordered by salary from highest to lowest.</p><p>We can also provide multiple properties:</p><pre>Pageable pageable = PageRequest.of(<br>        0,<br>        5,<br>        Sort.Direction.ASC,<br>        &quot;department&quot;,<br>        &quot;name&quot;<br>);</pre><p>Here, employees are sorted by:</p><pre>department → ASC<br>name       → ASC</pre><p>So, <strong>of(int page, int size, Sort.Direction direction, String... properties) creates a </strong><strong>PageRequest with pagination and sorting direction for one or more properties.</strong></p><h3>4. ofSize()</h3><p>The ofSize() method is used to <strong>create a </strong><strong>PageRequest for the first page with the specified page size</strong>.</p><p>It is useful when we want to create a basic PageRequest without explicitly specifying the page number.</p><h4>Method Signature</h4><pre>static PageRequest ofSize(int pageSize);</pre><h4>Return Type</h4><pre>PageRequest</pre><p>Returns a PageRequest representing the <strong>first page with the specified page size</strong>.</p><h4>Parameters</h4><pre>int pageSize</pre><p>The number of records required per page.</p><h4>Important Points</h4><ul><li>It always creates a PageRequest for <strong>page 0</strong>.</li><li>pageSize specifies the number of records required per page.</li><li>pageSize must be greater than 0.</li><li>No sorting is applied by this method.</li><li>It is a static method, so it is called using PageRequest.ofSize().</li><li>It is equivalent to:</li></ul><pre>PageRequest.of(0, pageSize)</pre><p>Suppose we want to retrieve <strong>5 employees per page</strong>, starting from the first page:</p><pre>PageRequest pageRequest = PageRequest.ofSize(5);<br>System.out.println(&quot;Page Number: &quot;<br>        + pageRequest.getPageNumber());<br>System.out.println(&quot;Page Size: &quot;<br>        + pageRequest.getPageSize());</pre><p><strong>Output:</strong></p><pre>Page Number: 0<br>Page Size: 5</pre><p>We can directly use it with a repository:</p><pre>Page&lt;Employee&gt; employeePage =<br>        employeeRepository.findAll(PageRequest.ofSize(5));</pre><p>Here:</p><pre>Page Number → 0<br>Page Size   → 5</pre><p>So, <strong>ofSize() creates a </strong><strong>PageRequest for the first page with the specified number of records per page.</strong></p><h3>Introduction to Sort</h3><p>When working with pagination and database queries in Spring Data JPA, we may need to control <strong>the order in which records are returned</strong>. Sort is used for this purpose.</p><h4>What is Sort?</h4><p>Sort is a <strong>class in Spring Data</strong> that provides a convenient way to define <strong>sorting information</strong> for query results.</p><p>It allows us to specify:</p><ul><li>Which property should be sorted</li><li>Sorting direction — ASC or DESC</li><li>Multiple properties for sorting</li></ul><h4>Where is Sort present?</h4><p>Sort is present in the:</p><pre>org.springframework.data.domain</pre><p>package.</p><p>It can be imported using:</p><pre>import org.springframework.data.domain.Sort;</pre><h4>Definition</h4><blockquote><strong><em>Sort is a class used to define sorting information for database query results in Spring Data.</em></strong></blockquote><p>For example:</p><pre>Sort sort = Sort.by(&quot;salary&quot;).descending();</pre><p>Here:</p><pre>Property  → salary<br>Direction → DESC</pre><p>This means the records will be sorted by salary in <strong>descending order</strong>.</p><h3>1. Sort.by(Direction direction, String... properties) ⭐</h3><p>The Sort.by(Direction direction, String... properties) method is used to <strong>create a </strong><strong>Sort object with a specified sorting direction for one or more properties</strong>.</p><h4>Method Signature</h4><pre>static Sort by(Direction direction, String... properties);</pre><h4>Return Type</h4><pre>Sort</pre><p>Returns a Sort object containing the specified <strong>sorting direction and properties</strong>.</p><h4>Parameters</h4><p>Direction direction:Defines the sorting direction: ASC or DESC.</p><p>String... properties:One or more entity properties/fields on which sorting should be applied.</p><h4>Important Points</h4><ul><li>Direction.ASC sorts in <strong>ascending order</strong>.</li><li>Direction.DESC sorts in <strong>descending order</strong>.</li><li>properties is a <strong>varargs parameter</strong>, so we can provide one or multiple properties.</li><li>The properties should match the <strong>entity property names</strong> used in the query.</li><li>The resulting Sort can be passed to PageRequest.</li></ul><h4>Example</h4><p>Suppose we want to sort employees by salary in descending order:</p><pre>Sort sort = Sort.by(<br>        Sort.Direction.DESC,<br>        &quot;salary&quot;<br>);<br>Pageable pageable = PageRequest.of(<br>        0,<br>        5,<br>        sort<br>);<br><br>Page&lt;Employee&gt; page =<br>        employeeRepository.findAll(pageable);</pre><p>Here:</p><pre>Page Number → 0<br>Page Size   → 5<br>Sort        → salary DESC</pre><p><strong>Multiple Properties</strong></p><pre>Sort sort = Sort.by(<br>        Sort.Direction.ASC,<br>        &quot;department&quot;,<br>        &quot;name&quot;<br>);</pre><h4>2.Sort.by(String... properties) ⭐</h4><p>The Sort.by(String... properties) method is used to <strong>create a </strong><strong>Sort object using one or more property names</strong>.</p><p>The sorting direction is <strong>ascending by default</strong>.</p><p><strong>Method Signature</strong></p><pre>public static Sort by(String... properties)</pre><p><strong>Return Type</strong></p><pre>Sort</pre><p><strong>Parameters</strong></p><pre>String... properties</pre><p>One or more property names that should be used for sorting.</p><p>Because properties is a <strong>varargs</strong> parameter, we can provide:</p><pre>Sort.by(&quot;name&quot;);</pre><p>or multiple properties:</p><pre>Sort.by(&quot;department&quot;, &quot;name&quot;);</pre><h4>Important Points</h4><ul><li>properties must not be null.</li><li>It accepts <strong>one or more properties</strong>.</li><li>The default direction is <strong>ascending (</strong><strong>ASC)</strong>.</li><li>If no properties are provided:</li></ul><pre>Sort.by()</pre><p>it returns an <strong>unsorted </strong><strong>Sort</strong>.</p><ul><li>Internally, the method creates a Sort object using the default direction and the provided properties.</li><li>We can change the direction using:</li></ul><pre>ascending()</pre><p>or</p><pre>descending()</pre><h4>Example</h4><p><strong>Single Property</strong></p><pre>Sort sort = Sort.by(&quot;name&quot;);</pre><p>This creates sorting as:</p><pre>name → ASC</pre><p><strong>Multiple Properties</strong></p><pre>Sort sort = Sort.by(&quot;department&quot;, &quot;name&quot;);</pre><p>This creates:</p><pre>department → ASC<br>name       → ASC</pre><p>The data is first sorted by department. If multiple records have the same department, name is used as the next sorting property.</p><h3>3. ascending() ⭐</h3><p>The ascending() method is used to <strong>create a new </strong><strong>Sort object that sorts the properties in ascending order</strong>.</p><p>It is useful when we want to sort data from <strong>lowest to highest</strong> or <strong>A to Z</strong>.</p><h4>Method Signature</h4><pre>Sort ascending();</pre><h4>Return Type</h4><pre>Sort</pre><p>Returns a new Sort object with the sorting direction set to <strong>ascending (</strong><strong>ASC)</strong>.</p><h4>Parameters</h4><p><strong>No parameters.</strong></p><p>The method uses the properties already defined in the current Sort object.</p><ul><li>It changes the sorting direction to <strong>ascending (</strong><strong>ASC)</strong>.</li><li>It does not modify the original Sort object; it returns a <strong>new </strong><strong>Sort object</strong>.</li><li>For numbers → <strong>lowest to highest</strong>.</li><li>For strings → generally <strong>A to Z</strong>.</li><li>It can be chained directly after Sort.by().</li></ul><h4>Example</h4><pre>Sort sort = Sort.by(&quot;salary&quot;).ascending();</pre><p>Here:</p><pre>Property  → salary<br>Direction → ASC</pre><p>We can use it with PageRequest:</p><pre>Pageable pageable = PageRequest.of(<br>        0,<br>        5,<br>        Sort.by(&quot;salary&quot;).ascending()<br>);<br>Page&lt;Employee&gt; page =<br>        employeeRepository.findAll(pageable);</pre><p>The employees will be sorted by salary from <strong>lowest to highest</strong>.</p><p>So, <strong>ascending() creates a </strong><strong>Sort with ascending order for the properties already defined in the </strong><strong>Sort object.</strong></p><h3>4.descending() ⭐</h3><p>The descending() method is used to <strong>create a new </strong><strong>Sort object that sorts the properties in descending order</strong>.</p><p>It is useful when we want to sort data from <strong>highest to lowest</strong> or <strong>Z to A</strong>.</p><h4>Method Signature</h4><pre>Sort descending();</pre><h4>Return Type</h4><pre>Sort</pre><p>Returns a new Sort object with the sorting direction set to <strong>descending (</strong><strong>DESC)</strong>.</p><h4>Parameters</h4><p><strong>No parameters.</strong></p><p>The method uses the properties already defined in the current Sort object.</p><h4>Important Points</h4><ul><li>It changes the sorting direction to <strong>descending (</strong><strong>DESC)</strong>.</li><li>It does not modify the original Sort object; it returns a <strong>new </strong><strong>Sort object</strong>.</li><li>For numbers → <strong>highest to lowest</strong>.</li><li>For strings → generally <strong>Z to A</strong>.</li><li>It can be chained directly after Sort.by().</li></ul><h4>Example</h4><h4>Single Property</h4><pre>Sort sort = Sort.by(&quot;salary&quot;).descending();</pre><p>Here:</p><pre>Property  → salary<br>Direction → DESC</pre><p>The employees will be sorted by salary from <strong>highest to lowest</strong>.</p><h4>Multiple Properties</h4><pre>Sort sort = Sort.by(&quot;department&quot;, &quot;name&quot;).descending();</pre><p>Here:</p><pre>department → DESC<br>name       → DESC</pre><p>The data is first sorted by department in descending order. If multiple records have the same department, name is then used in descending order.</p><p>We can use it with PageRequest:</p><pre>Pageable pageable = PageRequest.of(<br>        0,<br>        5,<br>        Sort.by(&quot;department&quot;, &quot;name&quot;).descending()<br>);<br>Page&lt;Employee&gt; page =<br>        employeeRepository.findAll(pageable);</pre><p>So, <strong>descending() creates a </strong><strong>Sort with descending order for the properties already defined in the </strong><strong>Sort object.</strong></p><h3>5.and(Sort sort) ⭐</h3><p>The and(Sort sort) method is used to <strong>combine the current </strong><strong>Sort object with another </strong><strong>Sort object</strong>.</p><p>It is useful when we want to <strong>apply sorting on multiple properties with different sorting directions</strong>.</p><h4>Method Signature</h4><pre>Sort and(Sort sort);</pre><h4>Return Type</h4><p>Returns a <strong>new </strong><strong>Sort object</strong> containing the sorting orders from both Sort objects.</p><h4>Parameters</h4><pre>Sort sort</pre><p>The Sort object that we want to <strong>combine with the current </strong><strong>Sort</strong>.</p><h4>Important Points</h4><ul><li>It combines two Sort objects.</li><li>We can use <strong>different sorting directions</strong> for different properties.</li><li>The original Sort objects are not modified.</li><li>It returns a <strong>new </strong><strong>Sort object</strong>.</li><li>The order in which the properties are combined is maintained.</li><li>It is useful when sorting by multiple properties with different directions.</li></ul><h4>Example</h4><p>Suppose we want to sort employees:</p><ul><li>First by department in ascending order.</li><li>Then by salary in descending order.</li></ul><p>We can create two Sort objects:</p><pre>Sort departmentSort =<br>        Sort.by(&quot;department&quot;).ascending();<br><br>Sort salarySort =<br>        Sort.by(&quot;salary&quot;).descending();</pre><p>Now combine them using and():</p><pre>Sort sort = departmentSort.and(salarySort);</pre><p>The sorting will be:</p><pre>department → ASC<br>salary     → DESC</pre><p>We can use it with PageRequest:</p><pre>Pageable pageable = PageRequest.of(<br>        0,<br>        5,<br>        sort<br>);<br><br>Page&lt;Employee&gt; page =<br>        employeeRepository.findAll(pageable);</pre><p>Here, employees are first sorted by <strong>department in ascending order</strong>. For employees belonging to the same department, they are sorted by <strong>salary in descending order</strong>.</p><p>So, <strong>and(Sort sort) combines two </strong><strong>Sort objects into a single </strong><strong>Sort, allowing us to apply multiple sorting conditions with different directions.</strong></p><h3>6.isSorted() ⭐</h3><p>The isSorted() method is used to <strong>check whether sorting is defined in the current </strong><strong>Sort object</strong>.</p><p>It is useful when we want to know whether a query has any sorting information.</p><h4>Method Signature</h4><pre>boolean isSorted();</pre><h4>Return Type</h4><pre>boolean</pre><p>Returns:</p><ul><li>true → if sorting is defined.</li><li>false → if no sorting is defined.</li></ul><h4>Parameters</h4><p><strong>No parameters.</strong></p><h4>Important Points</h4><ul><li>It checks whether the Sort object contains sorting information.</li><li>It returns true when at least one property is configured for sorting.</li><li>It returns false when the Sort is unsorted.</li><li>It does not change the Sort object.</li><li>It is commonly useful for checking sorting before processing or displaying pagination information.</li></ul><h4>Example</h4><p><strong>When sorting is defined</strong></p><pre>Sort sort = Sort.by(&quot;salary&quot;).descending();<br>System.out.println(sort.isSorted());</pre><p><strong>Output:</strong></p><pre>true</pre><p><strong>When sorting is not defined</strong></p><pre>Sort sort = Sort.unsorted();<br>System.out.println(sort.isSorted());</pre><p><strong>Output:</strong></p><pre>false</pre><p>So, <strong>isSorted() returns </strong><strong>true if the </strong><strong>Sort object contains sorting information; otherwise, it returns </strong><strong>false.</strong></p><h3>7.getOrderFor(String property) ⭐</h3><p>The getOrderFor(String property) method is used to <strong>find the sorting order configured for a specific property</strong> in the current Sort object.</p><p>It is useful when we want to check whether a particular property is sorted and determine its <strong>direction</strong>, such as ASC or DESC.</p><h4>Method Signature</h4><pre>Order getOrderFor(String property);</pre><h4>Return Type</h4><pre>Order</pre><p>Returns:</p><ul><li>An <strong>Order object</strong> → if the specified property has a sorting configuration.</li><li><strong>null</strong> → if the specified property is not configured for sorting.</li></ul><h4>Parameters</h4><p>String property:-The name of the property whose sorting order needs to be found.</p><h4>Important Points</h4><ul><li>It searches for the specified property in the current Sort object.</li><li>If the property is present, it returns its corresponding <strong>Order</strong> object.</li><li>The Order object contains information such as:</li></ul><pre>Property name<br>Direction (ASC or DESC)</pre><ul><li>If the property is not present, it returns null.</li><li>It <strong>does not modify</strong> the existing Sort object.</li><li>The method is useful when we need to inspect the sorting configuration for a particular property.</li></ul><h4>Example</h4><p><strong>When the property is present</strong></p><pre>Sort sort = Sort.by(&quot;salary&quot;).descending();<br>Sort.Order order = sort.getOrderFor(&quot;salary&quot;);<br>System.out.println(order);</pre><p><strong>Output:</strong></p><pre>salary: DESC</pre><p>We can also check the direction:</p><pre>System.out.println(order.getDirection());</pre><p><strong>Output:</strong></p><pre>DESC</pre><p><strong>When the property is not present</strong></p><pre>Sort sort = Sort.by(&quot;salary&quot;).descending();<br>Sort.Order order = sort.getOrderFor(&quot;empName&quot;);<br>System.out.println(order);</pre><p><strong>Output:</strong></p><pre>null</pre><p><strong>In short, </strong><strong>getOrderFor(String property) returns the </strong><strong>Order configuration for the specified property, or </strong><strong>null if that property is not being sorted.</strong></p><h3>8.unsorted() ⭐</h3><p>The unsorted() method is a <strong>static factory method</strong> used to create a Sort object that represents <strong>no sorting</strong>.</p><p>It is useful when we want to explicitly tell Spring Data that <strong>no sorting should be applied</strong> to the query.</p><h4>Method Signature</h4><pre>public static Sort unsorted();</pre><h4>Return Type</h4><pre>Sort</pre><p>Returns a <strong>Sort object</strong> with no sorting properties or orders configured.</p><h4>Parameters</h4><p><strong>No parameters.</strong></p><h4>Important Points</h4><ul><li>It is a <strong>static method</strong>, so we call it using the class name:</li></ul><pre>Sort.unsorted();</pre><ul><li>It creates a Sort object representing <strong>no sorting</strong>.</li><li>The returned Sort object has no Order objects.</li><li>isSorted() returns false for the returned object.</li><li>It is useful when sorting is optional or when we explicitly don’t want sorting.</li><li>It is commonly used with Pageable when pagination is required but sorting is not.</li></ul><h4>Example</h4><pre>Sort sort = Sort.unsorted();<br><br>System.out.println(sort.isSorted());</pre><p><strong>Output:</strong></p><pre>false</pre><p><strong>Example with </strong><strong>Pageable</strong></p><pre>Sort sort = Sort.unsorted();<br><br>Pageable pageable = PageRequest.of(0, 10, sort);</pre><p>Here:</p><ul><li>Page number → 0</li><li>Page size → 10</li><li>Sorting → <strong>Not applied</strong></li></ul><p>In short, Sort.unsorted() creates and returns a Sort object that represents the absence of sorting.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68e4a529e9be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pageable-Spring Data JPA]]></title>
            <link>https://medium.com/@varkalerushikesh/pageable-spring-data-jpa-fceb49016672?source=rss-ea54b0b43ef2------2</link>
            <guid isPermaLink="false">https://medium.com/p/fceb49016672</guid>
            <category><![CDATA[pageable]]></category>
            <category><![CDATA[sorting]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[pagination]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Rushikesh Anil Varkale ]]></dc:creator>
            <pubDate>Thu, 27 Aug 2026 11:11:37 GMT</pubDate>
            <atom:updated>2026-08-27T11:11:37.431Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction to Pageable</h3><p>When working with pagination in Spring Data JPA, we need a way to specify <strong>which page we want, how many records should be displayed per page, and how the data should be sorted</strong>. This is where Pageable is used.</p><h3>What is Pageable?</h3><p>Pageable is an <strong>interface in Spring Data</strong> that represents pagination information such as:</p><ul><li>Page number</li><li>Page size</li><li>Sorting information</li></ul><p>It is commonly passed to repository methods to request a specific page of data.</p><h3>Where is Pageable present?</h3><p>Pageable is present in the:</p><pre>org.springframework.data.domain</pre><p>package.</p><p>It can be imported using:</p><pre>import org.springframework.data.domain.Pageable;</pre><h3>Definition</h3><blockquote><strong><em>Pageable is an interface used to define pagination and sorting information for a database query.</em></strong></blockquote><p>For example:</p><pre>Pageable pageable = PageRequest.of(0, 10);</pre><p>This means:</p><pre>Page Number → 0 (first page)<br>Page Size   → 10 records</pre><p>Pageable is an <strong>interface</strong>, while PageRequest is one of its commonly used implementations for creating pagination requests.</p><p>In the following sections, we will look at the important methods provided by Pageable.</p><h3>1. getPageNumber() ⭐</h3><p>The getPageNumber() method is used to <strong>get the current page number represented by the </strong><strong>Pageable object</strong>.</p><p>It is useful when we want to know <strong>which page is being requested</strong>.</p><h4>Method Signature</h4><pre>int getPageNumber();</pre><h4>Return Type</h4><pre>int</pre><p>Returns the <strong>zero-based page number</strong>.</p><h4>Important Points</h4><ul><li>Page numbering starts from <strong>0</strong>.</li></ul><pre>0 represents the first page.<br>1 represents the second page.</pre><ul><li>It returns the page number stored in the Pageable object.</li><li>It is different from Page.getNumber():</li></ul><pre>Pageable.getPageNumber() → page number being requested.<br>Page.getNumber() → page number of the returned page.</pre><p><strong>Example</strong></p><pre>Pageable pageable = PageRequest.of(2, 5);<br><br>int pageNumber = pageable.getPageNumber();<br><br>System.out.println(&quot;Page Number: &quot; + pageNumber);</pre><p><strong>Output:</strong></p><pre>Page Number: 2</pre><p>Here, page number 2 represents the <strong>third page</strong>, because pagination is zero-based.</p><h3>2. getPageSize() ⭐</h3><p>The getPageSize() method is used to <strong>get the number of records requested per page</strong>.</p><h4>Method Signature</h4><pre>int getPageSize();</pre><h4>Return Type</h4><pre>int</pre><p>Returns the <strong>page size</strong>, i.e., the number of records requested for each page.</p><h4>Important Points</h4><ul><li>It returns the number of records requested per page.</li><li>For example, if we create:</li></ul><pre>PageRequest.of(0, 10);</pre><p>then getPageSize() returns 10.</p><ul><li>The page size is independent of the current page number.</li><li>It is different from Page.getNumberOfElements():</li><li>getPageSize() → number of records <strong>requested per page</strong>.</li><li>getNumberOfElements() → number of records <strong>actually present on the current page</strong>.</li><li>The actual number of records can be less than the page size, especially on the last page.</li></ul><p><strong>Example</strong></p><pre>Pageable pageable = PageRequest.of(0, 5);<br>int pageSize = pageable.getPageSize();<br>System.out.println(&quot;Page Size: &quot; + pageSize);</pre><p><strong>Output:</strong></p><pre>Page Size: 5</pre><p>Suppose the database contains 12 employees:</p><pre>Page 0 → 5 employees<br>Page 1 → 5 employees<br>Page 2 → 2 employees</pre><p>For all these pages:</p><pre>pageable.getPageSize();</pre><p>represents the requested page size of <strong>5</strong>.</p><h3>3. getOffset() ⭐</h3><p>The getOffset() method is used to <strong>get the position from which records should be retrieved for the current page</strong>.</p><p>It is useful for determining <strong>how many records should be skipped before retrieving the records for the requested page</strong>.</p><h4>Method Signature</h4><pre>long getOffset();</pre><h4>Return Type</h4><pre>long</pre><p>Returns the <strong>offset value</strong>, which represents the number of records to skip before the current page.</p><h4>Important Points</h4><ul><li>The offset is calculated using:</li></ul><pre>offset = page number × page size</pre><ul><li>Page numbering starts from 0.</li><li>For page 0, the offset is 0.</li><li>For page 1 with page size 10, the offset is 10.</li><li>For page 2 with page size 10, the offset is 20.</li><li>It is commonly used internally when generating paginated database queries.</li><li>The return type is long because the offset can be a large value.</li></ul><h4>Example</h4><pre>Pageable pageable = PageRequest.of(2, 5);<br>long offset = pageable.getOffset();<br>System.out.println(&quot;Offset: &quot; + offset);</pre><p><strong>Output:</strong></p><pre>Offset: 10</pre><p>Because:</p><pre>Page Number = 2<br>Page Size   = 5<br>Offset = 2 × 5<br>       = 10</pre><p>This means the database should <strong>skip the first 10 records</strong> and start retrieving records from that position.</p><pre>Records:  1  2  3  4  5  6  7  8  9  10 | 11  12  13  14  15<br>                                           ↑<br>                                         Offset 10</pre><p>So, <strong>getOffset() returns the number of records to skip before retrieving the records for the current page.</strong></p><h3>4. getSort() ⭐</h3><p>The getSort() method is used to <strong>get the sorting information specified in the </strong><strong>Pageable object</strong>.</p><p>It is useful when we want to know <strong>which field or fields the result should be sorted by and in which direction</strong>.</p><h4>Method Signature</h4><pre>Sort getSort();</pre><h4>Return Type</h4><pre>Sort</pre><h4>Important Points</h4><ul><li>It returns the sorting configuration specified in the Pageable.</li><li>Sorting can be:</li></ul><pre>Ascending<br>Descending</pre><ul><li>Multiple properties can also be used for sorting.</li><li>If no sorting is specified, it returns an <strong>unsorted </strong><strong>Sort object</strong>.</li><li>The returned Sort object can be used to check whether sorting is applied using methods such as:</li></ul><pre>isSorted()<br>isUnsorted()</pre><h4>Example</h4><p>Suppose we want to retrieve employees with their salary in descending order:</p><pre>Pageable pageable = PageRequest.of(<br>        0,<br>        5,<br>        Sort.by(&quot;salary&quot;).descending()<br>);<br>Sort sort = pageable.getSort();<br>System.out.println(sort);</pre><p><strong>Output:</strong></p><pre>salary: DESC</pre><p>We can also check whether sorting is applied:</p><pre>if (pageable.getSort().isSorted()) {<br>    System.out.println(&quot;Sorting is applied.&quot;);<br>}</pre><p><strong>Output:</strong></p><pre>Sorting is applied.</pre><p>So, <strong>getSort() returns the sorting information specified in the </strong><strong>Pageable object.</strong></p><h3>5. next() ⭐</h3><p>The next() method is used to <strong>create a new </strong><strong>Pageable object representing the next page while keeping the same page size and sorting information</strong>.</p><p>It is useful when we want to move from the current page to the <strong>next page</strong>.</p><h4>Method Signature</h4><pre>Pageable next();</pre><h4>Return Type</h4><pre>Pageable</pre><p>Returns a <strong>new </strong><strong>Pageable object for the next page</strong>.</p><h4>Important Points</h4><ul><li>It increases the current page number by <strong>1</strong>.</li><li>The page size remains the same.</li><li>The sorting information remains the same.</li><li>It does not modify the existing Pageable; it returns a <strong>new </strong><strong>Pageable object</strong>.</li><li>If the current page is 2, next() returns a Pageable for page 3.</li><li>next() only creates the Pageable; it does <strong>not execute the database query</strong>.</li><li>It can be used to request the next page from a repository.</li></ul><h4>Example</h4><p>Suppose the current Pageable represents <strong>page 1 with 5 records per page</strong>:</p><pre>Pageable pageable = PageRequest.of(1, 5);<br>System.out.println(&quot;Current Page: &quot; + pageable.getPageNumber());<br>Pageable nextPageable = pageable.next();<br>System.out.println(&quot;Next Page: &quot; + nextPageable.getPageNumber());</pre><p><strong>Output:</strong></p><pre>Current Page: 1<br>Next Page: 2</pre><p>We can then use the returned Pageable to retrieve the next page:</p><pre>Page&lt;Employee&gt; nextPage =<br>        employeeRepository.findAll(nextPageable);</pre><p>So, <strong>next() returns a new </strong><strong>Pageable representing the next page while preserving the current page size and sorting information.</strong></p><h3>6. previousOrFirst() ⭐</h3><p>The previousOrFirst() method is used to <strong>create a </strong><strong>Pageable for the previous page, or return a </strong><strong>Pageable for the first page if the current page is already the first page</strong>.</p><h4>Method Signature</h4><pre>Pageable previousOrFirst();</pre><h4>Return Type</h4><pre>Pageable</pre><p>Returns a Pageable representing either the <strong>previous page</strong> or the <strong>first page</strong>.</p><h4>Important Points</h4><ul><li>If the current page is greater than 0, it returns a Pageable for the previous page.</li><li>If the current page is 0, it returns a Pageable for page 0 itself.</li><li>It keeps the same page size and sorting information.</li><li>It does not modify the existing Pageable; it returns a <strong>new </strong><strong>Pageable object</strong>.</li><li>It is useful for safely navigating backward through pages.</li><li>It does not execute a database query; it only creates the Pageable.</li></ul><h4>Example</h4><h4>When a previous page exists</h4><pre>Pageable pageable = PageRequest.of(2, 5);<br>Pageable previousPageable = pageable.previousOrFirst();<br>System.out.println(&quot;Current Page: &quot;<br>        + pageable.getPageNumber());<br>System.out.println(&quot;Previous Page: &quot;<br>        + previousPageable.getPageNumber());</pre><p><strong>Output:</strong></p><pre>Current Page: 2<br>Previous Page: 1</pre><h4>When the current page is the first page</h4><pre>Pageable pageable = PageRequest.of(0, 5);<br><br>Pageable previousPageable = pageable.previousOrFirst();<br><br>System.out.println(previousPageable.getPageNumber());</pre><p><strong>Output:</strong></p><pre>0</pre><p>So, <strong>previousOrFirst() returns the previous page&#39;s </strong><strong>Pageable when available; otherwise, it returns the first page&#39;s </strong><strong>Pageable.</strong></p><h3>7. withPage() ⭐</h3><p>The withPage() method is used to <strong>create a new </strong><strong>Pageable object for a specific page number while keeping the existing page size and sorting information</strong>.</p><p>It is useful when we want to <strong>directly move to a particular page</strong>.</p><h4>Method Signature</h4><pre>Pageable withPage(int pageNumber);</pre><h4>Return Type</h4><pre>Pageable</pre><p>Returns a <strong>new </strong><strong>Pageable object representing the specified page</strong>.</p><h4>Parameters</h4><pre>int pageNumber</pre><ul><li>It allows us to directly specify the page number.</li><li>Page numbering is <strong>zero-based</strong>.</li><li>The existing page size is retained.</li><li>The existing sorting information is retained.</li><li>It does not modify the existing Pageable; it returns a <strong>new </strong><strong>Pageable object</strong>.</li><li>The pageNumber must not be negative.</li><li>It does not execute a database query; it only creates a new Pageable.</li></ul><h4>Example</h4><p>Suppose the current Pageable is for page 1, with 5 records per page and sorting by name:</p><pre>Pageable pageable = PageRequest.of(<br>        1,<br>        5,<br>        Sort.by(&quot;name&quot;).ascending()<br>);</pre><p>Now, we want to directly create a Pageable for <strong>page 3</strong>:</p><pre>Pageable pageThree = pageable.withPage(3);<br>System.out.println(&quot;Page Number: &quot;<br>        + pageThree.getPageNumber());<br>System.out.println(&quot;Page Size: &quot;<br>        + pageThree.getPageSize());<br>System.out.println(&quot;Sort: &quot;<br>        + pageThree.getSort());</pre><p><strong>Output:</strong></p><pre>Page Number: 3<br>Page Size: 5<br>Sort: name: ASC</pre><p>We can then use it with the repository:</p><pre>Page&lt;Employee&gt; employeePage =<br>        employeeRepository.findAll(pageThree);</pre><p>So, <strong>withPage() creates a new </strong><strong>Pageable for the specified page while retaining the existing page size and sorting information.</strong></p><h3>8. ofSize() ⭐</h3><p>The ofSize() method is used to <strong>create a </strong><strong>Pageable for the first page with the specified page size</strong>.</p><p>It is useful when we want to create a basic Pageable without explicitly specifying the page number.</p><h4>Method Signature</h4><pre>static Pageable ofSize(int pageSize);</pre><h4>Return Type</h4><pre>Pageable</pre><p>Returns a Pageable representing the <strong>first page with the specified page size</strong>.</p><h4>Parameters</h4><pre>int pageSize</pre><p>The number of records requested per page.</p><h4>Important Points</h4><ul><li>It creates a Pageable for <strong>page 0</strong>, which is the first page.</li><li>The specified value becomes the page size.</li><li>It is a <strong>static method</strong>, so it is called using Pageable.ofSize().</li><li>The pageSize must be greater than 0.</li><li>No sorting is specified by ofSize(), so the returned Pageable is unsorted.</li><li>If we need another page, we can use methods such as withPage() or next().</li></ul><h4>Example</h4><pre>Pageable pageable = Pageable.ofSize(5);<br>System.out.println(&quot;Page Number: &quot; + pageable.getPageNumber());<br>System.out.println(&quot;Page Size: &quot; + pageable.getPageSize());</pre><p><strong>Output:</strong></p><pre>Page Number: 0<br>Page Size: 5</pre><p>We can directly use it with a repository:</p><pre>Page&lt;Employee&gt; employeePage =<br>        employeeRepository.findAll(Pageable.ofSize(5));</pre><p>This requests:</p><pre>Page Number → 0<br>Page Size   → 5</pre><p>So, <strong>ofSize() creates a </strong><strong>Pageable for the first page with the specified number of records per page.</strong></p><h3>9. unpaged() ⭐</h3><p>The unpaged() method is used to <strong>create a </strong><strong>Pageable object that indicates that pagination is not required</strong>.</p><p>It is useful when we want to use a method that accepts a Pageable, but we want to <strong>retrieve all records without applying pagination</strong>.</p><h4>Method Signature</h4><pre>static Pageable unpaged();</pre><h4>Return Type</h4><pre>Pageable</pre><p>Returns an <strong>unpaged </strong><strong>Pageable object</strong>.</p><h4>Important Points</h4><ul><li>It indicates that <strong>pagination is not applied</strong>.</li><li>It is a <strong>static method</strong>, so it is called using:</li></ul><pre>Pageable.unpaged()</pre><ul><li>It can be passed to repository methods that accept a Pageable.</li><li>isPaged() returns false.</li><li>isUnpaged() returns true.</li><li>It is different from Pageable.ofSize():</li><li>ofSize() → pagination is enabled.</li><li>unpaged() → pagination is disabled.</li><li>Although pagination is disabled, sorting can be specified separately using Pageable.unpaged(Sort).</li></ul><h4>Example</h4><p>Suppose our repository method is:</p><pre>Page&lt;Employee&gt; findAll(Pageable pageable);</pre><p>If we want to retrieve the records <strong>without pagination</strong>:</p><pre>Pageable pageable = Pageable.unpaged();<br>Page&lt;Employee&gt; page =<br>        employeeRepository.findAll(pageable);</pre><p>We can check whether pagination is applied:</p><pre>System.out.println(pageable.isPaged());<br>System.out.println(pageable.isUnpaged());</pre><p><strong>Output:</strong></p><pre>false<br>true</pre><p>So, <strong>Pageable.unpaged() creates a </strong><strong>Pageable that indicates that no pagination should be applied.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fceb49016672" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Page<T> in Spring Data JPA]]></title>
            <link>https://medium.com/@varkalerushikesh/page-t-in-spring-data-jpa-405ce940757d?source=rss-ea54b0b43ef2------2</link>
            <guid isPermaLink="false">https://medium.com/p/405ce940757d</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[jparepository]]></category>
            <category><![CDATA[spring-data-jpa]]></category>
            <category><![CDATA[pagination]]></category>
            <dc:creator><![CDATA[Rushikesh Anil Varkale ]]></dc:creator>
            <pubDate>Wed, 26 Aug 2026 07:04:21 GMT</pubDate>
            <atom:updated>2026-08-26T07:04:21.878Z</atom:updated>
            <content:encoded><![CDATA[<p>When we retrieve a large number of records from a database, fetching all records at once is generally not a good approach. It can consume more memory, increase response time, and make the application less efficient.</p><p>For example, suppose an Employee table contains <strong>10,000 records</strong>. Instead of retrieving all 10,000 employees at once, we may want to retrieve:</p><ul><li>Page 0 → 10 employees</li><li>Page 1 → 10 employees</li><li>Page 2 → 10 employees</li><li>and so on.</li></ul><p>This approach is called <strong>pagination</strong>.</p><p>Spring Data JPA provides the Page&lt;T&gt; interface to represent the result of a <strong>paginated query</strong>.</p><h3>What is Page&lt;T&gt;?</h3><p>Page&lt;T&gt; represents <strong>a single page of data along with pagination information</strong>, such as the current page, page size, total number of elements, total number of pages, and whether the next or previous page exists.</p><h3>Where is Page&lt;T&gt; present?</h3><p>Page&lt;T&gt; is present in the org.springframework.data.domain package.</p><pre>import org.springframework.data.domain.Page;</pre><p>Its declaration is:</p><pre>public interface Page&lt;T&gt; extends Slice&lt;T&gt;</pre><p>Here, T represents the type of objects contained in the page.</p><p>For example:</p><pre>Page&lt;Employee&gt;</pre><p>represents a page containing Employee objects.</p><h3>Definition</h3><blockquote><strong><em>Page&lt;T&gt; is an interface used to represent a page of data along with information about the complete paginated result.</em></strong></blockquote><p>Since Page&lt;T&gt; extends Slice&lt;T&gt;, it also provides methods defined by Slice, such as getContent(), getNumber(), getSize(), hasNext(), and hasPrevious().</p><p>In addition, Page&lt;T&gt; provides methods such as getTotalElements() and getTotalPages() to get information about the complete result.</p><h3>1. getContent():</h3><p>The getContent() method is used to <strong>retrieve the records present in the current page</strong> as a List.</p><p>Since Page&lt;T&gt; represents one page of data, getContent() gives us the actual data contained in that page.</p><h4>Method Signature</h4><pre>List&lt;T&gt; getContent();</pre><h4>Return Type</h4><pre>List&lt;T&gt;</pre><p>Returns the <strong>list of elements present in the current page</strong>.</p><h4>Parameters</h4><p><strong>No parameters.</strong></p><h4>Important Points</h4><ul><li>getContent() returns only the records of the <strong>current page</strong>, not all records from the database.</li><li>The returned type is List&lt;T&gt;.</li><li>T represents the type of object stored in the Page.</li><li>If the current page has no records, it returns an <strong>empty list</strong>.</li><li>It is one of the most commonly used methods when working with Page&lt;T&gt;.</li><li>The method is actually defined in the parent Slice&lt;T&gt; interface and is inherited by Page&lt;T&gt;.</li></ul><h4>Example</h4><p>Suppose we have an EmployeeRepository:</p><pre>public interface EmployeeRepository extends JpaRepository&lt;Employee, Integer&gt; {<br>}</pre><p>We create a Pageable object to request <strong>page 0 with 3 employees per page</strong>:</p><pre>Pageable pageable = PageRequest.of(0, 3);<br>Page&lt;Employee&gt; page = employeeRepository.findAll(pageable);</pre><p>Now, we can get the employees present on the current page using getContent():</p><pre>List&lt;Employee&gt; employees = page.getContent();<br>employees.forEach(System.out::println);</pre><h3>2.getNumber()</h3><p>The getNumber() method is used to <strong>get the page number of the current page</strong>.</p><p>It is useful when we want to know <strong>which page is currently being processed</strong>.</p><h4>Method Signature</h4><pre>int getNumber();</pre><h4>Return Type</h4><pre>int</pre><p>Returns the <strong>zero-based number of the current page</strong>.</p><h4>Parameters</h4><p>No parameters.</p><h4>Important Points</h4><ul><li>Page numbering starts from <strong>0</strong>, not 1.</li><li>If we request:</li></ul><pre>PageRequest.of(0, 10);</pre><p>then getNumber() returns 0.</p><ul><li>If we request:</li></ul><pre>PageRequest.of(2, 10);</pre><p>then getNumber() returns 2.</p><ul><li>It returns only the <strong>current page number</strong>, not the total number of pages.</li><li>getNumber() is defined in the parent Slice&lt;T&gt; interface and inherited by Page&lt;T&gt;.</li></ul><p><strong>Example</strong></p><pre>Pageable pageable = PageRequest.of(2, 3);<br><br>Page&lt;Employee&gt; page = employeeRepository.findAll(pageable);<br><br>int currentPage = page.getNumber();<br><br>System.out.println(&quot;Current Page: &quot; + currentPage);</pre><p><strong>Output:</strong></p><pre>Current Page: 2</pre><p>Here, 2 means the <strong>third page</strong>, because Spring Data pagination uses <strong>zero-based page numbering</strong></p><h3>3.getSize()</h3><p>The getSize() method is used to <strong>get the requested page size.</strong>It helps us know <strong>how many records were requested per page</strong>.</p><h4>Method Signature</h4><pre>int getSize();</pre><p><strong>Return Type</strong></p><pre>int</pre><p>Returns the <strong>size of the current page</strong>.</p><h4><strong>Parameters</strong></h4><p>No parameters.</p><h4>Important Points</h4><ul><li>getSize() returns the <strong>page size specified in </strong><strong>Pageable</strong>.</li><li>For example, if we create:</li></ul><pre>PageRequest.of(0, 5);</pre><p>then getSize() returns 5.</p><ul><li>It represents the <strong>maximum number of records requested for a page</strong>.</li><li>getSize() and getNumberOfElements() are different:</li><li>getSize() → requested page size.</li><li>getNumberOfElements() → actual number of records present on the current page.</li><li>It is defined in the parent Slice&lt;T&gt; interface and inherited by Page&lt;T&gt;.</li></ul><p><strong>Example</strong></p><pre>Pageable pageable = PageRequest.of(0, 3);<br><br>Page&lt;Employee&gt; page = employeeRepository.findAll(pageable);<br><br>int pageSize = page.getSize();<br><br>System.out.println(&quot;Page Size: &quot; + pageSize);</pre><p><strong>Output</strong>:</p><pre>Page Size: 3</pre><p>Suppose the database has only <strong>2 records remaining</strong> on the last page:</p><pre>Requested page size = 3<br>Actual records       = 2</pre><p>In this case:</p><pre>page.getSize();             // 3<br>page.getNumberOfElements(); // 2</pre><p>So, <strong>getSize() tells us how many records were requested per page, not necessarily how many records are actually present.</strong></p><h3>4. getNumberOfElements()</h3><p>The getNumberOfElements() method is used to <strong>get the actual number of elements present on the current page</strong>.</p><p>It is useful when we want to know how many records were actually returned in the current page.</p><h4>Method Signature</h4><pre>int getNumberOfElements();</pre><h4>Return Type</h4><pre>int</pre><p>Returns the <strong>number of elements currently present in the page</strong>.</p><h4>Parameters</h4><p><strong>No parameters.</strong></p><h4>Important Points</h4><ul><li>It returns the <strong>actual number of records</strong> present on the current page.</li><li>It can be <strong>less than the page size</strong>.</li><li>It can be 0 if the current page contains no records.</li><li>It is different from getSize():</li><li>getSize() → maximum/requested number of records per page.</li><li>getNumberOfElements() → actual number of records present on the current page.</li><li>It is defined in the parent Slice&lt;T&gt; interface and inherited by Page&lt;T&gt;.</li></ul><h4>Example</h4><p>Suppose we request <strong>3 employees per page</strong>:</p><pre>Pageable pageable = PageRequest.of(1, 3);<br><br>Page&lt;Employee&gt; page = employeeRepository.findAll(pageable);<br><br>int numberOfElements = page.getNumberOfElements();<br><br>System.out.println(&quot;Number of Elements: &quot; + numberOfElements);</pre><p>Suppose the database has <strong>5 employees</strong>:</p><pre>Page 0 → Employee 1, Employee 2, Employee 3<br>Page 1 → Employee 4, Employee 5</pre><p>For page 1:</p><pre>Page Size              = 3<br>Actual Elements        = 2</pre><p>Therefore:</p><pre>page.getSize();             // 3<br>page.getNumberOfElements(); // 2</pre><p>So, <strong>getNumberOfElements() tells us how many records are actually present on the current page.</strong></p><h3>5.getTotalElements()</h3><p>It is useful when we want to know <strong>how many records exist in total</strong>, not just how many records are present on the current page.</p><h4>Method Signature</h4><pre>long getTotalElements();</pre><h4>Return Type</h4><pre>long</pre><h4>Parameters</h4><p><strong>No parameters.</strong></p><h4>Important Points</h4><ul><li>It returns the total number of records across <strong>all pages</strong>.</li><li>It is different from getNumberOfElements():</li><li>getNumberOfElements() → records on the <strong>current page</strong>.</li><li>getTotalElements() → <strong>total number of records in the complete result/database query</strong>.</li><li>The return type is long, because the total number of records can be very large.</li><li>It is declared directly in the Page&lt;T&gt; interface.</li><li>This information is useful for displaying pagination details such as:</li></ul><pre>Showing 11–20 of 100 employees</pre><ul><li>getTotalElements() represents the total result count, regardless of which page we are currently viewing.</li></ul><h4>Example</h4><p>Suppose the database contains <strong>25 employees</strong>, and we request <strong>5 employees per page</strong>:</p><pre>Pageable pageable = PageRequest.of(2, 5);<br>Page&lt;Employee&gt; page = employeeRepository.findAll(pageable);<br>long totalEmployees = page.getTotalElements();<br>System.out.println(&quot;Total Employees: &quot; + totalEmployees);</pre><p><strong>Output:</strong></p><pre>Total Employees: 25</pre><p>Even though the current page contains only 5 employees:</p><pre>page.getNumberOfElements(); // 5</pre><p>the total number of employees is:</p><pre>page.getTotalElements();    // 25</pre><p>So, <strong>getTotalElements() tells us the total number of records available across all pages.</strong></p><h3><strong>6. </strong><strong>getTotalPages() ⭐</strong></h3><p>It returns the total number of pages required to display all records.</p><h4>Method Signature</h4><pre>int getTotalPages();</pre><h4>Return Type</h4><pre>int</pre><p>Returns the <strong>total number of pages</strong>.</p><h4>Parameters</h4><p>No parameters.</p><h4>Important Points</h4><ul><li>It returns the total number of pages required to display all records.</li><li>The total pages are calculated based on:</li></ul><pre>Total number of records.<br>Page size.</pre><ul><li>It is useful for displaying pagination controls such as:</li></ul><pre>1  2  3  4  5</pre><ul><li>It is different from getNumber():</li><li>getNumber() → current page number.</li><li>getTotalPages() → total number of pages.</li><li>It is declared directly in the Page&lt;T&gt; interface.</li><li>If there are no records, getTotalPages() returns 0.</li></ul><h4>Example</h4><p>Suppose the database contains <strong>25 employees</strong>, and we request <strong>5 employees per page</strong>:</p><pre>Pageable pageable = PageRequest.of(0, 5);<br>Page&lt;Employee&gt; page = employeeRepository.findAll(pageable);<br>int totalPages = page.getTotalPages();<br>System.out.println(&quot;Total Pages: &quot; + totalPages);</pre><p><strong>Output:</strong></p><pre>Total Pages: 5</pre><p>Because:</p><pre>Total Records = 25<br>Page Size     = 5</pre><pre>Total Pages = 25 / 5 = 5</pre><p>If there are <strong>27 employees</strong> with a page size of <strong>5</strong>:</p><pre>Page 0 → 5 records<br>Page 1 → 5 records<br>Page 2 → 5 records<br>Page 3 → 5 records<br>Page 4 → 5 records<br>Page 5 → 2 records</pre><p>Therefore:</p><pre>page.getTotalPages(); // 6</pre><p>So, <strong>getTotalPages() tells us how many pages are required to display the complete result.</strong></p><h3>7. hasContent()</h3><p>The hasContent() method is used to <strong>check whether the current page contains any records</strong>.</p><p>It is useful when we want to determine whether the current page has data before processing or displaying it.</p><h4>Method Signature</h4><pre>boolean hasContent();</pre><h4>Return Type</h4><pre>boolean</pre><p>Returns:</p><ul><li>true → if the current page contains at least one record.</li><li>false → if the current page contains no records.</li></ul><h4>Parameters</h4><p><strong>No parameters.</strong></p><h4>Important Points</h4><ul><li>It checks only the <strong>current page</strong>, not the complete database result.</li><li>It returns true when the current page has one or more records.</li><li>It returns false when the current page is empty.</li><li>It is defined in the parent Slice&lt;T&gt; interface and inherited by Page&lt;T&gt;.</li><li>It can be used before processing the result to avoid working with an empty page.</li></ul><h4>Example</h4><pre>Pageable pageable = PageRequest.of(0, 5);<br><br>Page&lt;Employee&gt; page = employeeRepository.findAll(pageable);<br><br>if (page.hasContent()) {<br>    System.out.println(&quot;Employees found:&quot;);<br><br>    page.getContent().forEach(System.out::println);<br>} else {<br>    System.out.println(&quot;No employees found.&quot;);<br>}</pre><p>If the current page contains employees:</p><pre>Employees found:<br>Employee 1<br>Employee 2<br>Employee 3</pre><p>If the current page is empty:</p><pre>No employees found.</pre><p>So, <strong>hasContent() simply tells us whether the current page contains any records or not.</strong></p><h3>8. isFirst()</h3><p>The isFirst() method is used to <strong>check whether the current page is the first page of the result</strong>.</p><p>It is useful when we need to determine whether a <strong>previous page is available</strong>.</p><h4>Method Signature</h4><pre>boolean isFirst();</pre><h4>Return Type</h4><pre>boolean</pre><p>Returns:</p><ul><li>true → if the current page is the first page.</li><li>false → if the current page is not the first page.</li></ul><h4>Parameters</h4><p><strong>No parameters.</strong></p><h4>Important Points</h4><ul><li>Spring Data JPA uses <strong>zero-based page numbering</strong>.</li><li>Therefore, page 0 is considered the first page.</li><li>It checks only the position of the <strong>current page</strong>.</li><li>It is useful for controlling a <strong>Previous</strong> button in pagination.</li><li>It is defined in the parent Slice&lt;T&gt; interface and inherited by Page&lt;T&gt;.</li></ul><h4>Example</h4><pre>Pageable pageable = PageRequest.of(0, 5);<br><br>Page&lt;Employee&gt; page = employeeRepository.findAll(pageable);<br><br>if (page.isFirst()) {<br>    System.out.println(&quot;This is the first page.&quot;);<br>} else {<br>    System.out.println(&quot;Previous page is available.&quot;);<br>}</pre><p><strong>Output:</strong></p><pre>This is the first page.</pre><p>If we request page 2:</p><pre>Pageable pageable = PageRequest.of(2, 5);<br>Page&lt;Employee&gt; page = employeeRepository.findAll(pageable);<br>System.out.println(page.isFirst());</pre><p><strong>Output:</strong></p><pre>false</pre><p>So, <strong>isFirst() tells us whether the current page is the first page of the result.</strong></p><h3>9. isLast()</h3><p>The isLast() method is used to <strong>check whether the current page is the last page of the result</strong>.</p><p>It is useful when we need to determine whether a <strong>next page is available</strong>.</p><h4>Method Signature</h4><pre>boolean isLast();</pre><h4>Return Type</h4><pre>boolean</pre><p>Returns:</p><ul><li>true → if the current page is the last page.</li><li>false → if the current page is not the last page.</li></ul><h4>Parameters</h4><p><strong>No parameters.</strong></p><h4>Important Points</h4><ul><li>It checks whether the current page is the <strong>last available page</strong>.</li><li>It is useful for controlling a <strong>Next</strong> button in pagination.</li><li>If the current page is the last page, there is no next page to navigate to.</li><li>It is different from hasNext():</li><li>isLast() → checks whether the current page <strong>is the last page</strong>.</li><li>hasNext() → checks whether a <strong>next page exists</strong>.</li><li>It is defined in the parent Slice&lt;T&gt; interface and inherited by Page&lt;T&gt;.</li></ul><h4>Example</h4><p>Suppose there are <strong>12 employees</strong> and the page size is <strong>5</strong>:</p><pre>Page 0 → 5 employees<br>Page 1 → 5 employees<br>Page 2 → 2 employees</pre><p>If we request page 2:</p><pre>Pageable pageable = PageRequest.of(2, 5);<br>Page&lt;Employee&gt; page = employeeRepository.findAll(pageable);<br>if (page.isLast()) {<br>    System.out.println(&quot;This is the last page.&quot;);<br>} else {<br>    System.out.println(&quot;Next page is available.&quot;);<br>}</pre><p><strong>Output:</strong></p><pre>This is the last page.</pre><p>So, <strong>isLast() tells us whether the current page is the last page of the result.</strong></p><h3>10. hasNext()</h3><p>The hasNext() method is used to <strong>check whether a next page is available after the current page</strong>.</p><p>It is useful when we want to determine whether the user can navigate to the next page.</p><h4>Method Signature</h4><pre>boolean hasNext();</pre><h4>Return Type</h4><pre>boolean</pre><p>Returns:</p><ul><li>true → if a next page is available.</li><li>false → if there is no next page.</li></ul><h4>Parameters</h4><p><strong>No parameters.</strong></p><h4>Important Points</h4><ul><li>It checks whether a <strong>next page exists</strong> after the current page.</li><li>It is useful for enabling or disabling a <strong>Next</strong> button in a UI.</li><li>If the current page is the last page, it returns false.</li><li>It is different from isLast():</li><li><em>hasNext() → checks whether a </em><strong><em>next page is available</em></strong><em>.</em></li><li><em>isLast() → checks whether the </em><strong><em>current page is the last page</em></strong><em>.</em></li><li>It is defined in the parent Slice&lt;T&gt; interface and inherited by Page&lt;T&gt;.</li></ul><h4>Example</h4><p>Suppose there are <strong>12 employees</strong> and the page size is <strong>5</strong>:</p><pre>Page 0 → 5 employees<br>Page 1 → 5 employees<br>Page 2 → 2 employees</pre><p>If we are on page 1:</p><pre>Pageable pageable = PageRequest.of(1, 5);<br>Page&lt;Employee&gt; page = employeeRepository.findAll(pageable);<br>if (page.hasNext()) {<br>    System.out.println(&quot;Next page is available.&quot;);<br>} else {<br>    System.out.println(&quot;No next page.&quot;);<br>}</pre><p><strong>Output:</strong></p><pre>Next page is available.</pre><p>If we are on page 2:</p><pre>No next page.</pre><p>So, <strong>hasNext() tells us whether another page is available after the current page.</strong></p><h3>11. hasPrevious()</h3><p>The hasPrevious() method is used to <strong>check whether a previous page is available before the current page</strong>.</p><p>It is useful when we want to determine whether the user can navigate to the previous page.</p><h4>Method Signature</h4><pre>boolean hasPrevious();</pre><h4>Return Type</h4><pre>boolean</pre><p>Returns:</p><ul><li>true → if a previous page is available.</li><li>false → if there is no previous page.</li></ul><h4>Parameters</h4><p><strong>No parameters.</strong></p><h4>Important Points</h4><ul><li>It checks whether a <strong>previous page exists</strong> before the current page.</li><li>It is useful for enabling or disabling a <strong>Previous</strong> button in a UI.</li><li>If the current page is the first page, it returns false.</li><li>It is different from isFirst():</li><li>hasPrevious() → checks whether a <strong>previous page is available</strong>.</li><li>isFirst() → checks whether the <strong>current page is the first page</strong>.</li><li>It is defined in the parent Slice&lt;T&gt; interface and inherited by Page&lt;T&gt;.</li></ul><h4>Example</h4><p>Suppose there are <strong>12 employees</strong> and the page size is <strong>5</strong>:</p><pre>Page 0 → 5 employees<br>Page 1 → 5 employees<br>Page 2 → 2 employees</pre><p>If we are on page 1:</p><pre>Pageable pageable = PageRequest.of(1, 5);<br>Page&lt;Employee&gt; page = employeeRepository.findAll(pageable);<br>if (page.hasPrevious()) {<br>    System.out.println(&quot;Previous page is available.&quot;);<br>} else {<br>    System.out.println(&quot;No previous page.&quot;);<br>}</pre><p><strong>Output:</strong></p><pre>Previous page is available.</pre><p>If we are on page 0:</p><pre>No previous page.</pre><p>So, <strong>hasPrevious() tells us whether another page is available before the current page.</strong></p><h3>12. getSort()</h3><p>The getSort() method is used to <strong>get the sorting information applied to the current page</strong>.</p><p>It is useful when we want to know <strong>how the records in the page are sorted</strong>, such as by employee name, salary, or ID.</p><h4>Method Signature</h4><pre>Sort getSort();</pre><h4>Return Type</h4><pre>Sort</pre><p>Returns a Sort object containing the <strong>sorting information</strong> applied to the current page.</p><h4>Parameters</h4><p><strong>No parameters.</strong></p><h4>Important Points</h4><ul><li>It returns the sorting configuration used for the current page.</li><li>Sorting can be <strong>ascending</strong> or <strong>descending</strong>.</li><li>It is defined in the parent Slice&lt;T&gt; interface and inherited by Page&lt;T&gt;.</li><li>If no sorting is applied, it returns an <strong>unsorted </strong><strong>Sort object</strong>.</li><li>It is commonly used together with Pageable.</li></ul><h4>Example</h4><p>Suppose we want to retrieve employees with <strong>salary in descending order</strong>:</p><pre>Pageable pageable = PageRequest.of(<br>        0,<br>        5,<br>        Sort.by(&quot;salary&quot;).descending()<br>);<br>Page&lt;Employee&gt; page = employeeRepository.findAll(pageable);<br>Sort sort = page.getSort();<br>System.out.println(sort);</pre><p>The sorting information represents:</p><pre>salary → DESC</pre><p>We can also check whether sorting is applied:</p><pre>if (page.getSort().isSorted()) {<br>    System.out.println(&quot;Sorting is applied.&quot;);<br>}</pre><p><strong>Output:</strong></p><pre>Sorting is applied.</pre><p>So, <strong>getSort() returns the sorting information applied to the current page.</strong></p><h3>13. getPageable():</h3><p>The getPageable() method is used to <strong>get the </strong><strong>Pageable object that was used to request the current page</strong>.</p><p>It is useful when we need to get the <strong>current page number, page size, or sorting information</strong> from the Page.</p><h4>Method Signature</h4><pre>default Pageable getPageable();</pre><h4>Return Type</h4><pre>Pageable</pre><h4>Parameters</h4><p><strong>No parameters.</strong></p><h4>Important Points</h4><ul><li>It returns the Pageable information associated with the current page.</li><li>The returned Pageable contains information such as:</li></ul><pre>Current page number<br>Page size<br>Sorting information</pre><ul><li>It is defined as a <strong>default method</strong> in the parent Slice&lt;T&gt; interface.</li><li>Page&lt;T&gt; inherits this method from Slice&lt;T&gt;.</li><li>It is useful when we need to reuse the current pagination information.</li></ul><h4>Example</h4><pre>Pageable pageable = PageRequest.of(<br>        2,<br>        5,<br>        Sort.by(&quot;name&quot;).ascending()<br>);<br>Page&lt;Employee&gt; page = employeeRepository.findAll(pageable);<br>Pageable currentPageable = page.getPageable();<br>System.out.println(&quot;Page Number: &quot; + currentPageable.getPageNumber());<br>System.out.println(&quot;Page Size: &quot; + currentPageable.getPageSize());<br>System.out.println(&quot;Sort: &quot; + currentPageable.getSort());</pre><p><strong>Output:</strong></p><pre>Page Number: 2<br>Page Size: 5<br>Sort: name: ASC</pre><p>So, <strong>getPageable() returns the </strong><strong>Pageable object containing the pagination and sorting information used for the current page.</strong></p><h3>14. nextPageable():</h3><p>The nextPageable() method is used to <strong>get the </strong><strong>Pageable object required to request the next page of data</strong>.</p><p>It is useful when we want to <strong>navigate from the current page to the next page</strong>.</p><h4><strong>Method Signature</strong></h4><pre>Pageable nextPageable();</pre><h4>Return Type</h4><pre>Pageable</pre><p>Returns the Pageable object that can be used to <strong>request the next page</strong>.</p><h4>Parameters</h4><p><strong>No parameters.</strong></p><h4>Important Points</h4><ul><li>It returns the Pageable for the <strong>next page</strong>.</li><li>It should normally be called after checking hasNext().</li><li>If the current page is already the last page, it can return Pageable.unpaged().</li><li>It is defined in the parent Slice&lt;T&gt; interface and inherited by Page&lt;T&gt;.</li></ul><h4>Example</h4><p>Suppose we are currently on <strong>page 1</strong> with a page size of <strong>5</strong>:</p><pre>Pageable pageable = PageRequest.of(1, 5);<br>Page&lt;Employee&gt; page = employeeRepository.findAll(pageable);<br>if (page.hasNext()) {<br>    Pageable nextPageable = page.nextPageable();<br>    Page&lt;Employee&gt; nextPage = employeeRepository.findAll(nextPageable);<br>    nextPage.getContent().forEach(System.out::println);<br>}</pre><p>Here:</p><pre>Current Page → 1<br>Next Page    → 2<br>Page Size    → 5</pre><p>So, <strong>nextPageable() provides the </strong><strong>Pageable required to retrieve the next page of data.</strong></p><h3>15. previousPageable()</h3><p>The previousPageable() method is used to <strong>get the </strong><strong>Pageable object required to request the previous page of data</strong>.</p><p>It is useful when we want to <strong>navigate from the current page to the previous page</strong>.</p><h4>Method Signature</h4><pre>Pageable previousPageable();</pre><h4>Return Type</h4><pre>Pageable</pre><h4>Parameters</h4><p><strong>No parameters.</strong></p><h4>Important Points</h4><ul><li>It returns the Pageable for the <strong>previous page</strong>.</li><li>It should normally be called after checking hasPrevious().</li><li>If the current page is already the first page, it can return Pageable.unpaged().</li><li>It is defined in the parent Slice&lt;T&gt; interface and inherited by Page&lt;T&gt;.</li></ul><h4>Example</h4><pre>Pageable pageable = PageRequest.of(2, 5);<br><br>Page&lt;Employee&gt; page = employeeRepository.findAll(pageable);<br><br>if (page.hasPrevious()) {<br><br>    Pageable previousPageable = page.previousPageable();<br><br>    Page&lt;Employee&gt; previousPage =<br>            employeeRepository.findAll(previousPageable);<br><br>    previousPage.getContent().forEach(System.out::println);<br>}</pre><p>Here:</p><pre>Current Page  → 2<br>Previous Page → 1<br>Page Size     → 5</pre><p>So, <strong>previousPageable() provides the </strong><strong>Pageable required to retrieve the previous page of data.</strong></p><h3>16. map() ⭐</h3><p>The map() method is used to <strong>convert the content of the current </strong><strong>Page&lt;T&gt; from one type to another while keeping the pagination information</strong>.</p><p>It is especially useful for converting <strong>Entity objects into DTO objects</strong> before returning the data from an API.</p><h4>Method Signature</h4><pre>&lt;U&gt; Page&lt;U&gt; map(Function&lt;? super T, ? extends U&gt; converter);</pre><h4>Return Type</h4><pre>Page&lt;U&gt;</pre><p>Returns a <strong>new </strong><strong>Page containing the converted objects</strong>, while preserving the pagination information of the original page.</p><h4>Parameters</h4><pre>Function&lt;? super T, ? extends U&gt; converter</pre><p>A Function that defines <strong>how each element should be converted</strong> from type T to type U.</p><p>For example:</p><pre>Employee → EmployeeDTO</pre><h4>Important Points</h4><ul><li>map() converts <strong>each element in the current page</strong>.</li><li>It does <strong>not</strong> modify the original Page.</li><li>It returns a <strong>new </strong><strong>Page</strong> with the converted content.</li><li>Pagination information such as:</li></ul><pre>Current page<br>Page size<br>Total elements<br>Total pages</pre><p>remains available in the new Page.</p><ul><li>It is useful for <strong>Entity → DTO conversion</strong>.</li><li>It uses Java’s Function functional interface.</li><li>The method is declared in Page&lt;T&gt; and overrides the map() method inherited from Slice&lt;T&gt;.</li></ul><h4>Example</h4><p>Suppose we have an Employee entity:</p><pre>public class Employee {<br><br>    private Integer id;<br>    private String name;<br>    private double salary;<br><br>    // getters and setters<br>}</pre><p>And an EmployeeDTO:</p><pre>public class EmployeeDTO {<br><br>    private Integer id;<br>    private String name;<br><br>    public EmployeeDTO(Integer id, String name) {<br>        this.id = id;<br>        this.name = name;<br>    }<br><br>    // getters and setters<br>}</pre><p>First, retrieve employees as a Page&lt;Employee&gt;:</p><pre>Pageable pageable = PageRequest.of(0, 5);<br><br>Page&lt;Employee&gt; employeePage =<br>        employeeRepository.findAll(pageable);</pre><p>Now convert the Page&lt;Employee&gt; into Page&lt;EmployeeDTO&gt; using map():</p><pre>Page&lt;EmployeeDTO&gt; employeeDTOPage =<br>        employeePage.map(<br>            employee -&gt; new EmployeeDTO(<br>                employee.getId(),<br>                employee.getName()<br>            )<br>        );</pre><p>Now:</p><pre>Page&lt;Employee&gt;<br>      ↓<br>    map()<br>      ↓<br>Page&lt;EmployeeDTO&gt;</pre><p>The records are converted, but the pagination information is still available:</p><pre>employeeDTOPage.getContent();<br>employeeDTOPage.getTotalElements();<br>employeeDTOPage.getTotalPages();<br>employeeDTOPage.getNumber();</pre><p>So, <strong>map() is very useful when we need to convert the data inside a </strong><strong>Page from one object type to another without losing pagination information.</strong></p><h3>17. Page.empty()</h3><p>The Page.empty() method is used to <strong>create an empty </strong><strong>Page when there are no records to return</strong>.</p><p>It is useful when a method needs to return a Page&lt;T&gt; but there is no data available.</p><h4>Method Signature</h4><pre>static &lt;T&gt; Page&lt;T&gt; empty();</pre><h4>Return Type</h4><pre>Page&lt;T&gt;</pre><p>Returns an <strong>empty </strong><strong>Page</strong> with no content and no total elements.</p><h4>Parameters</h4><p><strong>No parameters.</strong></p><h4>Important Points</h4><ul><li>It returns an empty Page.</li><li>The returned page contains an <strong>empty list</strong>.</li><li>getTotalElements() returns 0.</li><li>getTotalPages() returns 0.</li><li>Since no Pageable is provided, it uses Pageable.unpaged().</li><li>It is a <strong>static method</strong>, so it is called using Page.empty().</li><li>This method is declared directly in the Page&lt;T&gt; interface.</li></ul><h4>Example</h4><p>Suppose we have a service method that needs to return a Page&lt;Employee&gt;:</p><pre>public Page&lt;Employee&gt; getEmployees(boolean returnEmpty) {<br>if (returnEmpty) {<br>        return Page.empty();<br>    }<br>    Pageable pageable = PageRequest.of(0, 5);<br>    return employeeRepository.findAll(pageable);<br>}</pre><p>When returnEmpty is true:</p><pre>Page&lt;Employee&gt; page = Page.empty();<br>System.out.println(page.getContent());<br>System.out.println(page.getTotalElements());<br>System.out.println(page.getTotalPages());</pre><p><strong>Output:</strong></p><pre>[]<br>0<br>0</pre><p>So, <strong>Page.empty() is used to return an empty </strong><strong>Page when there are no records to return.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=405ce940757d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JpaRepository in Spring Data JPA:]]></title>
            <link>https://medium.com/@varkalerushikesh/jparepository-in-spring-data-jpa-625e17249b2e?source=rss-ea54b0b43ef2------2</link>
            <guid isPermaLink="false">https://medium.com/p/625e17249b2e</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[sorting]]></category>
            <category><![CDATA[pagination]]></category>
            <category><![CDATA[jparepository]]></category>
            <dc:creator><![CDATA[Rushikesh Anil Varkale ]]></dc:creator>
            <pubDate>Fri, 21 Aug 2026 05:58:21 GMT</pubDate>
            <atom:updated>2026-08-21T05:58:21.130Z</atom:updated>
            <content:encoded><![CDATA[<p>If you have already worked with CrudRepository and ListCrudRepository, the next important interface to understand in Spring Data JPA is <strong>JpaRepository</strong>.</p><p>CrudRepository gives us basic CRUD operations.</p><p>ListCrudRepository gives us the same CRUD functionality while returning List instead of Iterable for methods that return multiple entities.</p><p>But what happens when we want <strong>pagination, sorting, JPA-specific operations, flushing, batch deletion, and entity references</strong>?</p><p>This is where JpaRepository becomes useful.</p><h3>1. What is JpaRepository?</h3><p>JpaRepository is an <strong>interface provided by Spring Data JPA</strong>.</p><pre>public interface JpaRepository&lt;T, ID&gt;<br>        extends ListCrudRepository&lt;T, ID&gt;,<br>                ListPagingAndSortingRepository&lt;T, ID&gt;,<br>                QueryByExampleExecutor&lt;T&gt; {<br>}</pre><p>So when we extend JpaRepository, we get much more than just basic CRUD operations.</p><p>For example:</p><pre>public interface EmployeeRepository<br>        extends JpaRepository&lt;Employee, Integer&gt; {<br>}</pre><p>Here:</p><ul><li>Employee → Entity type</li><li>Integer → Type of the Employee primary key</li></ul><p>Spring Data creates the repository implementation for us, so we normally do not need to implement this interface ourselves.</p><h4>2. Why Do We Prefer JpaRepository?</h4><p>Let’s compare what we have learned so far.</p><pre>CrudRepository<br>       ↓<br>Basic CRUD operations<br>--------------------------------------------------------------------------<br>ListCrudRepository<br>       ↓<br>CRUD + List return types<br>--------------------------------------------------------------------------<br><br>JpaRepository<br>       ↓<br>CRUD<br>+ List return types<br>+ Sorting<br>+ Pagination<br>+ JPA-specific operations<br>+ Flush operations<br>+ Batch delete operations<br>+ Entity references<br>+ Query By Example support</pre><h3>3. What Have We Already Covered?</h3><p>Before learning the new features of JpaRepository, we have already discussed two important repository interfaces:</p><ul><li>CrudRepository</li><li>ListCrudRepository</li></ul><p>Since JpaRepository extends ListCrudRepository, and ListCrudRepository is part of the CrudRepository hierarchy, the CRUD methods we already learned are also available when we use JpaRepository.</p><p>Therefore, <strong>we will not study those methods again in this article</strong>.</p><h4>CrudRepository</h4><p>In the previous article, we discussed the important CRUD methods provided by CrudRepository, such as:</p><pre>save()<br>saveAll()<br>findById()<br>findAll()<br>findAllById()<br>existsById()<br>count()<br>deleteById()<br>delete()<br>deleteAllById()<br>deleteAll()</pre><p>We already covered their:</p><ul><li>Return types</li><li>Parameters</li><li>Definitions</li><li>How they work</li><li>Practical examples</li><li>Important points</li></ul><p>So, when we use:</p><pre>public interface EmployeeRepository<br>        extends JpaRepository&lt;Employee, Integer&gt; {<br>}</pre><p>we can still use these CRUD methods.</p><p>There is no need to explain them again here.</p><h4>ListCrudRepository</h4><p>We also discussed ListCrudRepository and its important methods.ListCrudRepository provides the CRUD functionality of CrudRepository while changing the return type of methods that return multiple entities from Iterable to List.</p><p>For example:</p><pre>List&lt;Employee&gt; findAll();</pre><p>and:</p><pre>List&lt;Employee&gt; findAllById(Iterable&lt;Integer&gt; ids);</pre><p>We have already discussed these methods in detail in the <strong>ListCrudRepository</strong> article.</p><p>Since JpaRepository extends ListCrudRepository, these methods are also available through JpaRepository.</p><p>Therefore:</p><blockquote><strong><em>We will not repeat the </em></strong><strong><em>CrudRepository and </em></strong><strong><em>ListCrudRepository methods in this article.</em></strong></blockquote><p>Instead, we will focus on the <strong>new and important functionality that we have not discussed yet</strong>.</p><p>In this article, our main focus will be these three methods:</p><pre>getReferenceById(ID id)<br>findAll(Pageable pageable)<br>findAll(Sort sort)</pre><p>These will help us understand:</p><ul><li>How to get an entity reference using getReferenceById()</li><li>How pagination works using Pageable</li><li>How sorting works using Sort</li><li>How these features are available through JpaRepository</li></ul><h3>4.getReferenceById()</h3><p><em>It is used when we want to get a </em><strong><em>reference/proxy of an entity using its ID</em></strong><em>, rather than necessarily loading the complete entity data immediately.</em></p><h4>Method Signature</h4><pre>T getReferenceById(ID id);</pre><h4>Parameters</h4><ul><li>ID id → The primary key of the entity we want to reference.</li></ul><h4>Return type</h4><pre>T</pre><p>It returns an object of the entity type.</p><h4>Example</h4><p>Suppose we have:</p><pre>public interface EmployeeRepository<br>        extends JpaRepository&lt;Employee, Integer&gt; {<br>}</pre><p>We can write:</p><pre>Employee employee =<br>        employeeRepository.getReferenceById(101);</pre><p>Here:</p><ul><li>101 → Employee ID</li><li>Employee → Entity type</li><li>The returned value → Reference to the Employee entity</li></ul><h4>Why use it?</h4><p>Suppose we only need an Employee reference to set a relationship:</p><pre>Department department =<br>        departmentRepository.getReferenceById(10);<br><br>employee.setDepartment(department);</pre><p>In this situation, we may only need a reference to Department 10; we don&#39;t necessarily need to retrieve all Department details first.</p><h4>Important point</h4><p>getReferenceById() is different from:</p><pre>employeeRepository.findById(101);</pre><p>findById() is used when we want to <strong>retrieve the entity</strong>, and it returns:</p><pre>Optional&lt;Employee&gt;</pre><p>Whereas:</p><pre>getReferenceById(101);</pre><p>returns:</p><pre>Employee</pre><p>as an entity reference.</p><p>Also, if the referenced entity does not actually exist, the problem may not be detected at the moment getReferenceById() is called. It can be detected later when the reference is accessed, depending on the JPA provider.</p><h4>What happens if the ID does NOT exist?</h4><p>Suppose:</p><pre>Employee<br>----------------<br>ID    Name<br>101   Rahul<br>102   Amit</pre><p>Now we call:</p><pre>Employee employee =<br>        employeeRepository.getReferenceById(999);</pre><p>There is no employee with ID 999.</p><p><strong>Important:</strong> getReferenceById() may not immediately throw an exception when the method is called because it can return a reference/proxy first.</p><p>When the reference is actually accessed, JPA may throw:</p><pre>EntityNotFoundException</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*1vcyDNRboOA6xL7XXz59Kg.png" /></figure><h3>5.findAll(Sort sort)</h3><blockquote><strong><em>findAll(Sort sort) retrieves all entities from the database and returns them in the sorting order specified by the </em></strong><strong><em>Sort object.</em></strong></blockquote><p>It does <strong>not</strong> retrieve only some records.</p><p>It retrieves <strong>all records</strong>, but controls the order in which they are returned.</p><h4>Signature</h4><pre>List&lt;T&gt; findAll(Sort sort);</pre><h4>Return Type</h4><pre>List&lt;T&gt;</pre><ul><li>Returns a <strong>List of entities</strong>.</li><li>T represents the <strong>entity type</strong>.</li><li>The returned list contains entities <strong>sorted according to the given </strong><strong>Sort object</strong>.</li></ul><p>For example, if your repository is:</p><pre>public interface EmployeeRepository extends JpaRepository&lt;Employee, Integer&gt; {<br><br>}</pre><p>then:</p><pre>List&lt;T&gt; findAll(Sort sort);</pre><p>effectively becomes:</p><pre>List&lt;Employee&gt; findAll(Sort sort);</pre><h4>Parameter</h4><pre>Sort sort</pre><blockquote><em>Sort</em></blockquote><p>Sort is a Spring Data class used to specify:</p><ul><li><strong>Which field to sort by</strong></li><li><strong>Ascending or descending order</strong></li></ul><p>Import:</p><pre>import org.springframework.data.domain.Sort;</pre><p>Example:</p><pre>Sort.by(&quot;salary&quot;).ascending()</pre><p>means:</p><blockquote><em>Sort employees by salary in ascending order.</em></blockquote><h4>Where is this method present?</h4><p>List&lt;T&gt; findAll(Sort sort) is present in<em> ListPagingAndSortingRepository&lt;T, ID&gt;</em></p><h4>Example</h4><pre>Sort sort = Sort.by(&quot;salary&quot;).ascending();<br><br>List&lt;Employee&gt; employees = repo.findAll(sort);</pre><h3>6.findAll(Pageable pageable)</h3><blockquote><strong><em>findAll(Pageable pageable) retrieves entities from the database page by page according to the pagination and sorting information provided by the </em></strong><strong><em>Pageable object.</em></strong></blockquote><p>In simple words:</p><blockquote><strong><em>“Give me a particular number of records from a particular page, optionally in a particular sorting order.”</em></strong></blockquote><h4><em>Signature</em></h4><pre>Page&lt;T&gt; findAll(Pageable pageable);</pre><h4><em>Return Type</em></h4><pre>Page&lt;T&gt;</pre><ul><li>Returns a <strong>Page object</strong>, not a normal List.</li><li>T represents the <strong>entity type</strong>.</li><li>The Page contains the records for the <strong>current page</strong>.</li><li><em>It also provides useful pagination information such as:</em></li></ul><pre>Total number of records<br>Total number of pages<br>Current page number<br>Page size<br>Whether a next/previous page exists</pre><p>For example, if your repository is:</p><pre>public interface EmployeeRepository<br>        extends JpaRepository&lt;Employee, Integer&gt; {<br>}</pre><p>then:</p><pre>Page&lt;T&gt; findAll(Pageable pageable);</pre><p>effectively becomes:</p><pre>Page&lt;Employee&gt; findAll(Pageable pageable);</pre><h4><em>Parameter</em></h4><pre>Pageable pageable</pre><h4><em>Pageable</em></h4><p>Pageable is an interface that contains information about:</p><ul><li><strong>Which page to retrieve</strong></li><li><strong>How many records per page</strong></li><li><strong>How to sort the records</strong></li></ul><p>Import:</p><pre>import org.springframework.data.domain.Pageable;</pre><p>You normally create a Pageable using PageRequest.</p><pre>Pageable pageable = PageRequest.of(0, 5);</pre><p>This means:</p><blockquote><em>Get page number </em><em>0 and 5 records per page.</em></blockquote><p>Remember: <strong>page numbering starts from 0</strong>.</p><pre>Page 0 → First page<br>Page 1 → Second page<br>Page 2 → Third page</pre><h4><em>getContent() gives the actual records</em></h4><p>Suppose:</p><pre>Page&lt;Employee&gt; page = repo.findAll(pageable);</pre><p>To get the employees:</p><pre>List&lt;Employee&gt; employees = page.getContent();</pre><p>So remember:</p><pre>Page&lt;Employee&gt;<br> ↓<br>getContent()<br> ↓<br>List&lt;Employee&gt;</pre><h4>Page number starts from 0</h4><pre>PageRequest.of(0, 10);</pre><p>means:</p><p>Page 0 → First page</p><pre>PageRequest.of(1, 10);</pre><p>means:</p><p>Page 1 → Second page</p><h4>Second parameter represents page size</h4><pre>PageRequest.of(0, 10);</pre><p>Here:</p><p>0 → Page number<br>10 → Number of records per page</p><p>For example:</p><pre>PageRequest.of(0, 5);</pre><p>means:</p><p>Get the first page containing up to 5 records.</p><h4>Page contains pagination information</h4><p>Example:</p><pre>Page&lt;Employee&gt; page = repo.findAll(pageable);</pre><p>You can get the records using:</p><pre>List&lt;Employee&gt; employees = page.getContent();</pre><p>You can also get information such as:</p><pre>page.getTotalElements();<br>page.getTotalPages();<br>page.getNumber();<br>page.getSize();<br>page.hasNext();<br>page.hasPrevious();</pre><p>For example:</p><pre>System.out.println(page.getTotalElements());<br>System.out.println(page.getTotalPages());<br>System.out.println(page.getNumber());</pre><h4>You can combine pagination with sorting ⭐</h4><p>This is one of the most important uses.</p><pre>Pageable pageable =<br> PageRequest.of(<br> 0,<br> 5,<br> Sort.by(&quot;salary&quot;).descending()<br> );<br>Page&lt;Employee&gt; page = repo.findAll(pageable);</pre><p>This means:</p><p>Give me the first page, with 5 employees, sorted by salary from highest to lowest.</p><h4><em>Example</em></h4><pre>Pageable pageable = PageRequest.of(0, 5);<br><br>Page&lt;Employee&gt; page = repo.findAll(pageable);<br><br>List&lt;Employee&gt; employees = page.getContent();<br><br>employees.forEach(System.out::println);</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=625e17249b2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ListCrudRepository in Spring Data JPA]]></title>
            <link>https://medium.com/@varkalerushikesh/listcrudrepository-in-spring-data-jpa-05938b96b9b5?source=rss-ea54b0b43ef2------2</link>
            <guid isPermaLink="false">https://medium.com/p/05938b96b9b5</guid>
            <category><![CDATA[list-crud-repository]]></category>
            <category><![CDATA[crudrepository]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[spring-data-jpa]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Rushikesh Anil Varkale ]]></dc:creator>
            <pubDate>Thu, 20 Aug 2026 06:56:15 GMT</pubDate>
            <atom:updated>2026-08-20T06:56:15.338Z</atom:updated>
            <content:encoded><![CDATA[<p>When working with Spring Data JPA, we commonly use repository interfaces such as CrudRepository, ListCrudRepository, and JpaRepository.</p><p>In my previous article, we discussed <a href="https://medium.com/@varkalerushikesh/crudrepository-t-id-9caf6fbdc557">CrudRepository</a>, which provides ready-made methods for basic <strong>CRUD operations</strong> — Create, Read, Update, and Delete.</p><p>In this article, we will focus on <strong>ListCrudRepository</strong> and understand what makes it different from CrudRepository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6jZikWkjknguUIYiV6dwrg.png" /></figure><h3>1. What is ListCrudRepository?</h3><p>ListCrudRepository is an interface provided by Spring Data.</p><p>It extends CrudRepository and provides the same basic CRUD functionality, but with one important difference:</p><blockquote><strong><em>Methods that return multiple entities return a </em></strong><strong><em>List instead of an </em></strong><strong><em>Iterable.</em></strong></blockquote><p>ListCrudRepository was introduced in <strong>Spring Data 3.0</strong>.</p><p>The basic structure is:</p><pre>public interface ListCrudRepository&lt;T, ID&gt;<br>        extends CrudRepository&lt;T, ID&gt; {<br>}</pre><p>Here:</p><ul><li>T → Entity type</li><li>ID → Type of the entity&#39;s primary key</li></ul><p>For example:</p><pre>public interface EmployeeRepository<br>        extends ListCrudRepository&lt;Employee, Integer&gt; {<br>}</pre><p>Here:</p><ul><li>Employee is the entity type.</li><li>Integer is the type of the Employee primary key.</li></ul><h3>2. Why do we need ListCrudRepository?</h3><p>You may be wondering:</p><blockquote><strong><em>If </em></strong><strong><em>CrudRepository already exists, why was </em></strong><strong><em>ListCrudRepository introduced?</em></strong></blockquote><p>The main reason is the return type.</p><p>In CrudRepository, methods that return multiple records use Iterable.</p><p>For example:</p><pre>Iterable&lt;Employee&gt; findAll();</pre><p>But ListCrudRepository overrides this method and returns:</p><pre>List&lt;Employee&gt; findAll();</pre><p>This can be more convenient because List provides common collection operations such as:</p><pre>get()<br>size()<br>isEmpty()</pre><p>So the basic idea is:</p><pre>CrudRepository<br>       |<br>       | returns multiple entities as Iterable<br>       ↓<br>ListCrudRepository<br>       |<br>       | returns multiple entities as List<br>       ↓<br>More convenient collection handling</pre><h3>3. ListCrudRepository vs CrudRepository</h3><p>The important thing to understand is that <strong>ListCrudRepository does not replace all the methods of CrudRepository</strong>.</p><p>It inherits the CRUD methods from CrudRepository and specifically overrides the methods where multiple entities are returned.</p><p>There are <strong>3 overridden methods</strong>:</p><ol><li>saveAll()</li><li>findAll()</li><li>findAllById()</li></ol><h3>4. saveAll()</h3><h4>CrudRepository</h4><p>In CrudRepository:</p><pre>&lt;S extends T&gt; Iterable&lt;S&gt; saveAll(Iterable&lt;S&gt; entities);</pre><h4>ListCrudRepository</h4><p>ListCrudRepository overrides it as:</p><pre>&lt;S extends T&gt; List&lt;S&gt; saveAll(Iterable&lt;S&gt; entities);</pre><p>Notice the difference:</p><pre>CrudRepository:<br>Iterable&lt;S&gt;<br><br>ListCrudRepository:<br>List&lt;S&gt;</pre><p>The method still performs the same basic operation — saving multiple entities.</p><p>The main difference is the <strong>return type</strong>.</p><h4>Example</h4><pre>Employee employee1 =<br>        new Employee(101, &quot;Rahul&quot;, 50000);<br><br>Employee employee2 =<br>        new Employee(102, &quot;Amit&quot;, 60000);<br><br><br>List&lt;Employee&gt; employees =<br>        List.of(employee1, employee2);<br><br>List&lt;Employee&gt; savedEmployees =<br>        employeeRepository.saveAll(employees);</pre><p>Because we are using ListCrudRepository, the returned value is directly a List&lt;Employee&gt;.</p><p>With CrudRepository, we would receive:</p><pre>Iterable&lt;Employee&gt;</pre><p>With ListCrudRepository, we receive:</p><pre>List&lt;Employee&gt;</pre><h4>Important</h4><p>saveAll() does not necessarily mean only INSERT.</p><p>Generally:</p><pre>New entities      → INSERT<br>Existing entities → UPDATE</pre><p>So saveAll() can be used for both creating and updating multiple entities.</p><h3>5. findAll()</h3><p>This is probably the easiest difference to understand.</p><h4>CrudRepository</h4><pre>Iterable&lt;T&gt; findAll();</pre><h4>ListCrudRepository</h4><pre>List&lt;T&gt; findAll();</pre><p>Again:</p><pre>CrudRepository<br>      ↓<br>Iterable&lt;T&gt;<br><br>ListCrudRepository<br>      ↓<br>List&lt;T&gt;</pre><h4>Example</h4><p>Suppose our repository is:</p><pre>public interface EmployeeRepository<br>        extends ListCrudRepository&lt;Employee, Integer&gt; {<br>}</pre><p>We can retrieve all employees:</p><pre>List&lt;Employee&gt; employees =<br>        employeeRepository.findAll();</pre><p>Now we directly have a List&lt;Employee&gt;.</p><p>For example:</p><pre>System.out.println(employees.size());</pre><p>We can also access an employee using its index:</p><pre>Employee employee = employees.get(0);</pre><p>This is one of the main conveniences of ListCrudRepository.</p><h3>6. findAllById()</h3><p>This method is used when we want to retrieve <strong>multiple entities using their IDs</strong>.</p><h4>CrudRepository</h4><pre>Iterable&lt;T&gt; findAllById(Iterable&lt;ID&gt; ids);</pre><h4>ListCrudRepository</h4><pre>List&lt;T&gt; findAllById(Iterable&lt;ID&gt; ids);</pre><p>Again, only the return type changes:</p><pre>CrudRepository:<br>Iterable&lt;T&gt;<br><br>ListCrudRepository:<br>List&lt;T&gt;</pre><h4>Example</h4><p>Suppose we want employees with IDs:</p><pre>List&lt;Integer&gt; ids =<br>        List.of(101, 102, 103);</pre><p>We can write:</p><pre>List&lt;Employee&gt; employees =<br>        employeeRepository.findAllById(ids);</pre><p>The result is directly a List&lt;Employee&gt;.</p><p><em>If some IDs are not present, the result can contain fewer entities than the number of IDs supplied. Also, the order of the returned elements is not guaranteed.</em></p><h4>For example:</h4><pre>Requested IDs:</pre><pre>101<br>102<br>103</pre><pre>Database:</pre><pre>101 → exists<br>102 → exists<br>103 → does not exist</pre><pre>Result:</pre><pre>[Employee101, Employee102]</pre><h3>7.One Important Point</h3><p>You may see:</p><pre>ListCrudRepository&lt;Employee, Integer&gt;</pre><p>and think:</p><blockquote><em>“Does it contain only three methods?”</em></blockquote><p>No.</p><p>It <strong>inherits the other CRUD methods from </strong><strong>CrudRepository</strong>.</p><p>Conceptually:</p><p>So ListCrudRepository gives you the complete CRUD functionality of CrudRepository, while changing the return types of the three multi-result methods.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=05938b96b9b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CrudRepository<T, ID>]]></title>
            <link>https://medium.com/@varkalerushikesh/crudrepository-t-id-9caf6fbdc557?source=rss-ea54b0b43ef2------2</link>
            <guid isPermaLink="false">https://medium.com/p/9caf6fbdc557</guid>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[crud-repo]]></category>
            <category><![CDATA[crudrepository]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring-data-jpa]]></category>
            <dc:creator><![CDATA[Rushikesh Anil Varkale ]]></dc:creator>
            <pubDate>Wed, 19 Aug 2026 12:46:36 GMT</pubDate>
            <atom:updated>2026-08-19T12:46:36.409Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is CrudRepository?</h3><p>CrudRepository is an <strong>interface provided by Spring Data</strong> that gives us ready-made methods for performing basic database operations.</p><p>CRUD means:</p><ul><li><strong>C</strong> → Create</li><li><strong>R</strong> → Read</li><li><strong>U</strong> → Update</li><li><strong>D</strong> → Delete</li></ul><p>Example:</p><pre>public interface EmployeeRepository <br>        extends CrudRepository&lt;Employee, Integer&gt; {<br>}</pre><p>Here:</p><ul><li>Employee → Entity type</li><li>Integer → Type of Employee&#39;s primary key</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*1YJKgdEa7EU0auDSfvN-dg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*eeSLoz4NJ0hKav-SpkzhSg.png" /></figure><h4><strong><em>1]&lt;S extends T&gt; S save(S entity);</em></strong></h4><ul><li><strong>Definition:</strong> This method is used to <strong>save a new entity to the database or update an existing entity</strong> in the database.</li><li><strong>Why &lt;S extends T&gt;?</strong> Allows S to be the entity type T or a subclass of T, while returning the same type S.</li><li><strong>When to use:</strong> Whenever you want to create a new entity or update an existing entity.</li><li><strong>Important:</strong> save() does not always mean INSERT.</li></ul><pre>New entity → generally INSERT<br>Existing entity → generally UPDATE</pre><ul><li><strong>Example:</strong></li></ul><pre>Employee employee = new Employee();<br>employee.setEmpId(101);<br>employee.setEmpName(&quot;Rahul&quot;);<br>Employee savedEmployee = employeeRepository.save(employee);</pre><h4>2] &lt;S extends T&gt; Iterable&lt;S&gt; saveAll(Iterable&lt;S&gt; entities);</h4><ul><li><strong>Definition:</strong> This method is used to <strong>save multiple entities to the database</strong> at once. It can be used for creating new entities or updating existing entities.</li><li><strong>Why &lt;S extends T&gt;?</strong> Allows S to be the entity type T or a subclass of T, while returning the saved entities with the same type S.</li><li><strong>When to use:</strong> Whenever you want to <strong>save multiple entities together</strong> instead of calling save() separately for each entity.</li><li><strong>Important:</strong> saveAll() does not always mean INSERT.</li></ul><pre>New entities → generally INSERT<br>Existing entities → generally UPDATE</pre><ul><li><strong>Example:</strong></li></ul><pre>Employee employee1 = new Employee();<br>employee1.setEmpId(101);<br>employee1.setEmpName(&quot;Rahul&quot;);<br><br>Employee employee2 = new Employee();<br>employee2.setEmpId(102);<br>employee2.setEmpName(&quot;Amit&quot;);<br><br>List&lt;Employee&gt; employees = List.of(employee1, employee2);<br><br>Iterable&lt;Employee&gt; savedEmployees =<br>       employeeRepository.saveAll(employees);</pre><h4>3] Optional&lt;T&gt; findById(ID id);</h4><ul><li><strong>Definition:</strong> This method is used to <strong>find an entity from the database using its primary key (ID)</strong>.</li><li><strong>When to use:</strong> Whenever you want to <strong>retrieve a single entity by its ID</strong>.</li><li><strong>Important:</strong> findById() does not return null when no entity is found; it returns an empty Optional.</li><li><strong>Example:</strong></li></ul><pre>Optional&lt;Employee&gt; employee =<br>employeeRepository.findById(101);</pre><p>If employee 101 exists:</p><p><em>Optional[Employee]</em></p><p>If it doesn’t exist:</p><p><em>Optional.empty()</em></p><h3>4] boolean existsById(ID id);</h3><ul><li><strong>Definition:</strong> This method is used to <strong>check whether an entity with the given ID exists in the database</strong>.</li></ul><pre>Entity exists → true<br>Entity does not exist → false</pre><ul><li><strong>When to use:</strong> Whenever you want to <strong>check the existence of an entity before performing another operation</strong>.</li><li><strong>Important:</strong> It returns only true or false; it <strong>does not return the entity</strong>.</li><li><strong>Example:</strong></li></ul><pre>boolean exists = employeeRepository.existsById(101);</pre><p>If employee 101 exists:</p><p>true</p><p>If employee 101 does not exist:</p><p>False</p><h4>5] Iterable&lt;T&gt; findAll();</h4><ul><li><strong>Definition:</strong> This method is used to <strong>retrieve all entities from the database</strong>.</li><li><strong>Why Iterable&lt;T&gt;?</strong> It allows the method to return a collection of entities that can be iterated over.</li><li><strong>When to use:</strong> Whenever you want to <strong>fetch all records/entities</strong> from the corresponding database table.</li><li><strong>Example:</strong></li></ul><pre>Iterable&lt;Employee&gt; employees =<br>       employeeRepository.findAll();<br>//You can iterate through the result:<br>employees.forEach(System.out::println);</pre><h4>6] Iterable&lt;T&gt; findAllById(Iterable&lt;ID&gt; ids);</h4><ul><li><strong>Definition:</strong> This method is used to <strong>retrieve multiple entities from the database using their IDs</strong>.</li><li><strong>Why Iterable&lt;T&gt;?</strong> Because the method can return <strong>multiple entities</strong>, and Iterable&lt;T&gt; allows us to iterate through those entities.</li><li><strong>When to use:</strong> Whenever you want to <strong>fetch multiple specific entities by their primary keys</strong>.</li><li><strong>Important:</strong> If some IDs do not exist in the database, the method <strong>does not return an entity for those IDs</strong>. Therefore, the number of returned entities can be less than the number of IDs provided.(no exception if id is not present).</li><li><strong>Example:</strong></li></ul><pre>List&lt;Integer&gt; ids = List.of(101, 102, 103);<br>Iterable&lt;Employee&gt; employees =<br>employeeRepository.findAllById(ids);</pre><p>Here, employees with IDs 101, 102, and 103 are retrieved if they exist.</p><h4>7] long count();</h4><ul><li><strong>Definition:</strong> This method is used to <strong>get the total number of entities/records</strong> available in the database.</li><li><strong>Why long?</strong> Because the number of records can be very large, so the method returns the count as a long value.</li><li><strong>When to use:</strong> Whenever you want to <strong>know how many entities/records exist</strong> in the database.</li><li><strong>Example:</strong></li></ul><pre>long employeeCount =<br>employeeRepository.count();</pre><p>If there are 50 employees in the database:</p><p>employeeCount = 50</p><h4>8] void deleteById(ID id);</h4><ul><li><strong>Definition:</strong> This method is used to <strong>delete an entity from the database using its primary key (ID)</strong>.</li><li><strong>Why void?</strong> The method only performs the delete operation and <strong>does not return any value</strong>.</li><li><strong>When to use:</strong> Whenever you want to <strong>delete a specific entity by its ID</strong>.</li><li><strong>Important:</strong> If the entity with the given ID does not exist, the operation is <strong>silently ignored</strong>.</li><li><strong>Example:</strong></li></ul><pre>employeeRepository.deleteById(101);</pre><p>Here, the employee whose ID is 101 will be deleted from the database.</p><h4>9] void delete(T entity);</h4><ul><li><strong>Definition:</strong> This method is used to <strong>delete a specific entity from the database</strong> by passing the entity object itself.</li><li><strong>Why void?</strong> The method performs the delete operation and <strong>does not return any value</strong>.</li><li><strong>When to use:</strong> Whenever you already have the <strong>entity object</strong> that you want to delete.</li><li><strong>Important:</strong> Unlike deleteById(), this method accepts the <strong>entity object</strong>, not its ID.</li><li><strong>Example:</strong></li></ul><pre>Employee employee =<br>employeeRepository.findById(101)<br>.orElseThrow();<br>employeeRepository.delete(employee);</pre><p>Here, the Employee object with ID 101 is passed directly to delete(), and it will be deleted from the database.</p><h4>10] void deleteAllById(Iterable&lt;? extends ID&gt; ids);</h4><ul><li><strong>Definition:</strong> This method is used to <strong>delete multiple entities from the database using their IDs</strong>.</li><li><strong>Why void?</strong> The method performs the delete operation and <strong>does not return any value</strong>.</li><li><strong>Why Iterable&lt;? extends ID&gt;?</strong> It allows you to pass a collection of IDs, including IDs of a type that is a subclass of ID.</li><li><strong>When to use:</strong> Whenever you want to <strong>delete multiple specific entities by their primary keys</strong>.</li><li><strong>Important:</strong> If any of the given IDs do not exist, they are <strong>silently ignored</strong>.</li><li><strong>Example:</strong></li></ul><pre>List&lt;Integer&gt; ids = List.of(101, 102, 103);<br>employeeRepository.deleteAllById(ids);</pre><p>Here, employees with IDs 101, 102, and 103 will be deleted if they exist.</p><h4>11] void deleteAll(Iterable&lt;? extends T&gt; entities);</h4><ul><li><strong>Definition:</strong> This method is used to <strong>delete multiple specified entities from the database</strong>.</li><li><strong>Why void?</strong> The method performs the delete operation and <strong>does not return any value</strong>.</li><li><strong>Why Iterable&lt;? extends T&gt;?</strong> It allows you to pass a collection of entities of type T or a subclass of T.</li><li><strong>When to use:</strong> Whenever you want to <strong>delete multiple specific entity objects at once</strong>.</li><li><strong>Important:</strong> This method accepts <strong>entities</strong>, not IDs. If you want to delete using IDs, use deleteAllById().</li><li><strong>Example:</strong></li></ul><pre>List&lt;Employee&gt; employees = List.of(employee1, employee2);<br>employeeRepository.deleteAll(employees);</pre><p>Here, employee1 and employee2 will be deleted from the database.</p><h3>12] void deleteAll();</h3><ul><li><strong>Definition:</strong> This method is used to <strong>delete all entities managed by the repository from the database</strong>.</li><li><strong>Why void?</strong> The method performs the delete operation and <strong>does not return any value</strong>.</li><li><strong>When to use:</strong> Whenever you want to <strong>delete all records/entities</strong> of that repository.</li><li><strong>Important:</strong> This method takes <strong>no arguments</strong> and can delete <strong>all records</strong> associated with the repository, so use it carefully.</li><li><strong>Example:</strong></li></ul><pre>employeeRepository.deleteAll();</pre><p>Here, <strong>all Employee records</strong> managed by employeeRepository will be deleted from the database.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9caf6fbdc557" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[@Transactional in Spring — From Basic to Advanced]]></title>
            <link>https://medium.com/@varkalerushikesh/transactional-in-spring-from-basic-to-advanced-4fd08b1ac33d?source=rss-ea54b0b43ef2------2</link>
            <guid isPermaLink="false">https://medium.com/p/4fd08b1ac33d</guid>
            <category><![CDATA[spring-framework]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-data-jpa]]></category>
            <category><![CDATA[database-transaction]]></category>
            <dc:creator><![CDATA[Rushikesh Anil Varkale ]]></dc:creator>
            <pubDate>Tue, 18 Aug 2026 11:37:35 GMT</pubDate>
            <atom:updated>2026-08-18T11:37:35.644Z</atom:updated>
            <content:encoded><![CDATA[<p>When working with databases in Spring applications, we often perform multiple database operations as part of a single business operation.</p><p>For example, transferring money may involve:</p><ol><li>Deducting money from Account A.</li><li>Adding money to Account B.</li></ol><p>What happens if the first operation succeeds but the second fails?</p><p>We need a mechanism that ensures <strong>either all operations succeed or all operations are rolled back</strong>.</p><p>This is where Spring’s @Transactional comes into the picture.</p><ol><li><strong>What is </strong><strong>@Transactional?</strong></li></ol><p><a href="http://twitter.com/Transactional"><em>@Transactional</em></a><em> is a Spring annotation used to define a transaction boundary around a method or class.</em></p><p><em>A transaction is a group of database operations treated as one unit of work.</em></p><h4>Simple definition</h4><p><a href="http://twitter.com/Transactional"><em>@Transactional</em></a><em> ensures that a group of database operations either completes successfully as a whole or is rolled back when a failure occurs.</em></p><p>Example:</p><p><a href="http://twitter.com/Transactional"><em>@Transactional</em></a><em><br>public void transferMoney() {</em></p><p><em>debitAccount();</em></p><p><em>creditAccount();<br>}</em></p><p><strong><em>If both operations succeed:</em></strong></p><p><em>COMMIT</em></p><p><strong><em>If an error occurs:</em></strong></p><p><em>ROLLBACK</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qkVWI07rHV2X289AaB4LbQ.png" /></figure><h3>2.Basic Example of @Transactional</h3><p>Consider an Employee service:</p><pre>@Service<br>public class EmployeeService {<br>    @Transactional<br>    public void saveEmployee() {<br>        Employee employee = new Employee();<br>        employee.setEmpId(1);<br>        employee.setEmpName(&quot;Rahul&quot;);<br>        employee.setSalary(50000.0);<br>        employeeRepository.save(employee);<br>    }<br>}</pre><p>Here, Spring manages the transaction around saveEmployee().</p><p>Conceptually:</p><pre>Transaction starts<br>       ↓<br>save employee<br>       ↓<br>Method completes successfully<br>       ↓<br>COMMIT</pre><p>If an failure occurs:</p><pre>Transaction starts<br>       ↓<br>save employee<br>       ↓<br>Exception<br>       ↓<br>ROLLBACK</pre><h3>3. Where Should We Put @Transactional?</h3><p>The <strong>Service layer</strong> is the most common and recommended place to use @Transactional.</p><p><strong>Why Service layer?</strong></p><p>The Service layer usually represents a <strong>business operation</strong>. A single business operation may involve multiple database operations through one or more repositories.</p><p>For example:</p><pre>@Service<br>public class EmployeeService {<br><br>    @Transactional<br>    public void transferSalary(Integer employee1, Integer employee2) {<br>    <br>        Employee e1 = employeeRepository.findById(employee1)<br>                .orElseThrow();<br>    <br>        Employee e2 = employeeRepository.findById(employee2)<br>                .orElseThrow();<br>    <br>        e1.setSalary(e1.getSalary() - 1000);<br>        e2.setSalary(e2.getSalary() + 1000);<br>    }<br>}</pre><h3>4.@Transactional and Rollback</h3><p>One of the most important features of @Transactional is <strong>rollback</strong>.</p><h4>What is Rollback?</h4><p><strong>Rollback</strong> means undoing the database changes made during a transaction when the transaction cannot be completed successfully.</p><p>For example, suppose we save an employee and then an error occurs. If the transaction is rolled back, the employee will <strong>not be inserted into the database</strong>.</p><h3>Example</h3><pre>@Transactional<br>public void saveEmployee() {<br>Employee employee = new Employee();<br>    employee.setEmpId(1);<br>    employee.setEmpName(&quot;Rahul&quot;);<br>    employeeRepository.save(employee);<br>    throw new RuntimeException(&quot;Something went wrong&quot;);<br>}</pre><p>Here, two things happen:</p><ol><li>employeeRepository.save(employee) performs the save operation within the transaction.</li><li>A RuntimeException is thrown after the save operation.</li></ol><p>By default, <strong>Spring rolls back the transaction when an unchecked exception, such as </strong><strong>RuntimeException, is thrown</strong>.</p><p>Therefore, the employee insertion is rolled back.</p><h3>Execution Flow</h3><pre>saveEmployee()<br>      ↓<br>Start Transaction<br>      ↓<br>employeeRepository.save(employee)<br>      ↓<br>INSERT employee<br>      ↓<br>RuntimeException occurs<br>      ↓<br>Transaction is marked for rollback<br>      ↓<br>ROLLBACK<br>      ↓<br>INSERT is undone</pre><h3>Important Point ⭐</h3><p>By default:</p><blockquote><strong><em>When a </em></strong><strong><em>RuntimeException or other unchecked exception is thrown from a </em></strong><strong><em>@Transactional method, Spring rolls back the transaction.</em></strong></blockquote><p>For example:</p><pre>throw new RuntimeException(&quot;Something went wrong&quot;);</pre><p>This causes the transaction to roll back.</p><h3>What happens without @Transactional?</h3><p>If the operation is not part of a single transaction, Spring cannot treat the entire business operation as one unit of work.</p><p>For example:</p><pre>public void saveEmployee() {<br>employeeRepository.save(employee);<br>    throw new RuntimeException(&quot;Something went wrong&quot;);<br>}</pre><p>In this case, you should <strong>not assume that the </strong><strong>save() operation will be rolled back</strong> just because a RuntimeException occurred.</p><p>That is why @Transactional is important when multiple database operations need to succeed or fail together.</p><h3>In Simple Terms</h3><p>Think of a transaction like a single package of database operations:</p><blockquote><strong><em>Everything succeeds → COMMIT</em></strong></blockquote><blockquote><strong><em>A </em></strong><strong><em>RuntimeException occurs → ROLLBACK</em></strong></blockquote><p>So, @Transactional helps ensure that a business operation follows the <strong>&quot;all or nothing&quot;</strong> principle.</p><h3>5. Runtime Exception vs Checked Exception</h3><p>This is an important point.</p><p>By default, Spring’s transaction management rolls back for:</p><pre>RuntimeException</pre><p>But not automatically for every checked exception.</p><p>For example:</p><pre>@Transactional<br>public void saveEmployee() throws Exception {<br>employeeRepository.save(employee);<br>    throw new Exception(&quot;Checked exception&quot;);<br>}</pre><p>A checked exception does not automatically trigger rollback under the default rules.</p><h3>6. rollbackFor</h3><p>If you want a checked exception to trigger rollback, use:</p><pre>@Transactional(rollbackFor = Exception.class)<br>public void saveEmployee() throws Exception {<br>employeeRepository.save(employee);<br>    throw new Exception(&quot;Something went wrong&quot;);<br>}</pre><p>Now Spring is instructed to roll back for Exception.</p><h3>Simple rule</h3><pre>RuntimeException → rollback by default</pre><pre>Checked Exception → use rollbackFor when rollback is required</pre><h3>7. noRollbackFor</h3><p>Sometimes, we <strong>do not want a transaction to roll back for a specific exception</strong>.</p><p>For this purpose, Spring provides the noRollbackFor attribute of @Transactional.</p><p>Example:</p><pre>@Transactional(noRollbackFor = IllegalArgumentException.class)<br>public void saveEmployee() {<br><br>    employeeRepository.save(employee);<br><br>    throw new IllegalArgumentException(&quot;Invalid employee data&quot;);<br>}</pre><p>Normally, IllegalArgumentException is an <strong>unchecked exception (</strong><strong>RuntimeException)</strong>, so Spring would roll back the transaction.</p><p>However, by using:</p><pre>noRollbackFor = IllegalArgumentException.class</pre><p>we are telling Spring:</p><blockquote><strong><em>“Even if </em></strong><strong><em>IllegalArgumentException occurs, do not roll back this transaction.&quot;</em></strong></blockquote><h3>Execution Flow</h3><pre>saveEmployee()<br>      ↓<br>Start Transaction<br>      ↓<br>save employee<br>      ↓<br>IllegalArgumentException occurs<br>      ↓<br>NO ROLLBACK<br>      ↓<br>Transaction commits</pre><h4>8. What does readOnly = true actually mean?</h4><p>When you write:</p><pre>@Transactional(readOnly = true)<br>public List&lt;Employee&gt; getEmployees() {<br>    return employeeRepository.findAll();<br>}</pre><p>you are basically telling Spring:</p><blockquote><strong><em>“This transaction is intended for reading data. I don’t plan to modify the database.”</em></strong></blockquote><p>It is a <strong>hint</strong> to Spring and the underlying persistence provider that this transaction is for reading.</p><h3>Does it prevent save()?</h3><p><strong>No.</strong> Don’t think of readOnly = true as a permission or security restriction.</p><p>For example:</p><pre>@Transactional(readOnly = true)<br>public void test() {<br><br>    employeeRepository.save(employee);<br>}</pre><p>readOnly = true does <strong>not mean</strong>:</p><blockquote><em>“Spring will definitely throw an error whenever </em><em>save() is called.&quot;</em></blockquote><p>The exact behavior can depend on the JPA provider, database, and configuration. So you should <strong>not use </strong><strong>readOnly as a way to prevent writes</strong>.</p><h3>Why use it then?</h3><p>For a method that genuinely only reads data:</p><pre>@Transactional(readOnly = true)<br>public List&lt;Employee&gt; getEmployees() {<br>    return employeeRepository.findAll();<br>}</pre><p>it communicates your intention clearly:</p><pre>@Transactional<br>       ↓<br>&quot;This method performs database work&quot;<br><br>@Transactional(readOnly = true)<br>       ↓<br>&quot;This method is intended only for reading&quot;</pre><p>It can also allow the persistence provider/database to apply certain optimizations for read-oriented operations.</p><h3>Why use readOnly = true if the method is already doing only a read?</h3><p>Because you’re telling Hibernate:</p><blockquote><strong><em>“I’m only going to read entities in this transaction. Don’t spend unnecessary effort tracking them for updates.”</em></strong></blockquote><p>This is where <strong>dirty checking</strong> comes in.</p><p>Normally, Hibernate does dirty checking:</p><pre>@Transactional<br>public Employee getEmployee() {<br><br>    Employee employee = employeeRepository.findById(1).orElseThrow();<br><br>    employee.setSalary(50000.0);<br><br>    return employee;<br>}</pre><p>Hibernate keeps track of the entity. At transaction commit, it checks:</p><pre>Original Employee<br>       ↓<br>Employee was modified?<br>       ↓<br>YES<br>       ↓<br>Generate UPDATE SQL</pre><p>This is called <strong>dirty checking</strong>.</p><h3>What happens with readOnly = true?</h3><p>You’re telling Spring/Hibernate:</p><pre>&quot;This transaction is for reading.I don&#39;t intend to modify entities.&quot;</pre><p>Depending on the JPA provider/configuration, Hibernate can reduce or skip some dirty-checking work for entities loaded in that read-only transaction.</p><p>So the benefit is mainly:</p><p><strong>Read-only transaction → less unnecessary change-tracking work → potentially better performance for read-heavy operations.</strong></p><p><em>readOnly = true is useful for read-only operations because it tells Spring and the persistence provider that the transaction is intended only for reading. In Hibernate, this can reduce unnecessary dirty-checking and related persistence work, which may improve performance for read-heavy operations.</em></p><h3>9. timeout</h3><p>We can specify how long a transaction is allowed to run.</p><pre>@Transactional(timeout = 10)<br>public void processEmployee() {<br>}</pre><p>Here, the transaction timeout is specified as 10 seconds.</p><p>This can help prevent transactions from remaining active for an unnecessarily long time.</p><h3>10. @Transactional and Lazy Loading</h3><p>Lazy loading is an important concept in JPA and Hibernate, especially when working with entity relationships.</p><p>Consider the following example:</p><pre>@Entity<br>public class Department {<br>@OneToMany(fetch = FetchType.LAZY)<br>    private List&lt;Employee&gt; employees;<br>}</pre><p>Here, employees is configured with FetchType.LAZY.</p><p>This means:</p><blockquote><strong><em>Hibernate does not load the employees immediately when the Department is loaded. The employees are loaded only when the collection is accessed.</em></strong></blockquote><h3>What Happens with Lazy Loading?</h3><p>Suppose we execute:</p><pre>Department department =<br>        departmentRepository.findById(1).orElseThrow();</pre><p>Hibernate loads the Department.</p><p>However, because employees is lazy, Hibernate generally does not load all employees immediately.</p><p>Conceptually:</p><pre>findDepartment()<br>      ↓<br>Department loaded<br>      ↓<br>Employees not loaded yet<br>      ↓<br>department.getEmployees()<br>      ↓<br>Hibernate loads Employees</pre><p>This helps avoid loading unnecessary related data.</p><h3>What is the Problem?</h3><p>Lazy loading requires an appropriate <strong>persistence context</strong> when Hibernate needs to initialize the lazy relationship.</p><p>For example:</p><pre>Department department =<br>        departmentRepository.findById(1).orElseThrow();</pre><p>Later, if we access:</p><pre>department.getEmployees().size();</pre><p>Hibernate may need to execute another SQL query to load the employees.</p><p>If the persistence context is no longer available at that point, Hibernate cannot initialize the lazy collection.</p><p>This can result in:</p><pre>LazyInitializationException</pre><p>Conceptually:</p><pre>Department loaded<br>      ↓<br>Employees are still LAZY<br>      ↓<br>Persistence Context is no longer available<br>      ↓<br>getEmployees()<br>      ↓<br>Hibernate tries to load Employees<br>      ↓<br>Cannot initialize LAZY collection<br>      ↓<br>LazyInitializationException</pre><h4>A transactional service method can keep the persistence context available while the required data is accessed.</h4><p>The key idea is:</p><p><em>Access lazy-loaded data within an appropriate persistence context/transaction rather than relying on lazy loading after the context has closed.</em></p><h3>Important: @Transactional Does Not Disable Lazy Loading</h3><p>@Transactional does not change:</p><pre>FetchType.LAZY</pre><p>The relationship is still lazy.</p><p>Instead, @Transactional provides a transactional boundary in which the lazy relationship can be initialized.</p><h3>Key Takeaways ⭐</h3><ol><li><strong>FetchType.LAZY</strong> means related data is loaded only when it is accessed.</li><li>Lazy loading helps avoid loading unnecessary related data.</li><li>Hibernate needs an appropriate <strong>persistence context</strong> to initialize a lazy relationship.</li><li>If an uninitialized lazy relationship is accessed after the required persistence context is no longer available, LazyInitializationException may occur.</li><li>@Transactional provides a clear transactional boundary in which lazy data can be accessed.</li><li>Access required lazy relationships <strong>inside the transaction</strong>.</li><li>@Transactional does not make a lazy relationship eager; it simply provides an appropriate context for the lazy loading operation.</li></ol><h3>In One Sentence</h3><blockquote><strong><em>Lazy loading delays loading related data, and </em></strong><strong><em>@Transactional helps ensure that the required persistence context is available when Hibernate needs to load that data.</em></strong></blockquote><h3>11.Transaction Rollback Does Not Mean Everything Is Automatically Undone.</h3><p>Rollback applies to operations participating in the transaction.</p><p>For example, external operations such as:</p><pre>Sending an email<br>Calling another API<br>Writing a file<br>Publishing an external message</pre><p>are not automatically undone just because the database transaction rolls back.</p><p>Example:</p><pre>@Transactional<br>public void createEmployee() {<br>employeeRepository.save(employee);<br>    emailService.sendEmail();<br>}</pre><p>If the database transaction rolls back, Spring cannot magically “unsend” the email.</p><p>This becomes important in distributed systems.</p><h3>12. @Transactional on Class</h3><p>We can place @Transactional on a class:</p><pre>@Service<br>@Transactional<br>public class EmployeeService {<br><br>    public void saveEmployee() {<br>    }<br><br>    public void updateEmployee() {<br>    }<br><br>    public void deleteEmployee() {<br>    }<br>}</pre><p>The transaction configuration can apply to the methods in the class.</p><p>You can also override configuration at the method level.</p><pre>@Service <br>@Transactional <br>public class EmployeeService { <br>  public void saveEmployee() {<br>  } <br>  @Transactional(readOnly = true) <br>  public List&lt;Employee&gt; getEmployees() { <br>    return employeeRepository.findAll(); <br>  } <br>}</pre><p>The method-level configuration is more specific.</p><p><strong>putting </strong><strong>@Transactional on the class makes its public methods transactional by default, and a method-level </strong><strong>@Transactional can provide more specific transaction behavior.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4fd08b1ac33d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kadane’s Algorithm — Find Maximum Sum Subarray in Java]]></title>
            <link>https://medium.com/@varkalerushikesh/kadanes-algorithm-find-maximum-sum-subarray-in-java-7f22030ace0d?source=rss-ea54b0b43ef2------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f22030ace0d</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[coding-interviews]]></category>
            <dc:creator><![CDATA[Rushikesh Anil Varkale ]]></dc:creator>
            <pubDate>Wed, 22 Jul 2026 06:59:27 GMT</pubDate>
            <atom:updated>2026-07-22T06:59:27.333Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>One of the most frequently asked interview problems is finding the <strong>maximum sum contiguous subarray</strong>. It appears in interviews at companies like Google, Microsoft, Amazon, Meta, and many others.</p><p>We’ll first solve the problem using a simple approach, understand its limitations, and then optimize it using <strong>Kadane’s Algorithm</strong>, which solves the problem in <strong>O(n)</strong> time.</p><h3>Problem Statement</h3><p>Given an integer array, find the contiguous subarray having the maximum sum.</p><h4>Example</h4><pre>Input:<br>[2, -3, 4, -1, 2, 1, -5, 4]<br><br>Output:<br>6<br><br>Explanation:<br>The subarray [4, -1, 2, 1] has the maximum sum = 6.</pre><h3>Solution 1: Brute Force Approach</h3><h3>Idea</h3><p>The idea is simple.</p><p>Start from every index and calculate the sum of every possible subarray.</p><p>While calculating the sum, keep updating the maximum sum found so far.</p><h3>Step-by-Step</h3><p>Suppose the array is</p><pre>[2, -3, 4]</pre><p>Starting from index <strong>0</strong></p><pre>[2]          Sum = 2<br>[2,-3]       Sum = -1<br>[2,-3,4]     Sum = 3</pre><p>Starting from index <strong>1</strong></p><pre>[-3]         Sum = -3<br>[-3,4]       Sum = 1</pre><p>Starting from index <strong>2</strong></p><pre>[4]          Sum = 4</pre><p>The maximum is <strong>4</strong>.</p><h3>Java Code</h3><pre>public class BruteForce {<br><br>    public static void main(String[] args) {<br><br>        int[] arr = {2, -3, 4, -1, 2, 1, -5, 4};<br><br>        int maxSum = Integer.MIN_VALUE;<br><br>        for (int i = 0; i &lt; arr.length; i++) {<br><br>            int currentSum = 0;<br><br>            for (int j = i; j &lt; arr.length; j++) {<br><br>                currentSum += arr[j];<br><br>                if (currentSum &gt; maxSum) {<br>                    maxSum = currentSum;<br>                }<br>            }<br>        }<br><br>        System.out.println(&quot;Maximum Sum = &quot; + maxSum);<br>    }<br>}</pre><h3>How it Works</h3><p>Outer loop selects the starting index.</p><pre>i = 0</pre><p>Inner loop keeps extending the subarray.</p><pre>2<br>2,-3<br>2,-3,4<br>2,-3,4,-1<br>...</pre><p>After that,</p><p>Outer loop moves to</p><pre>i = 1</pre><p>Again all possible subarrays are calculated.</p><p>This process continues until every possible subarray is checked.</p><h3>Time Complexity</h3><pre>Outer Loop  -&gt; n<br>Inner Loop  -&gt; n<br><br>Time Complexity = O(n²)</pre><h3>Why Do We Need a Better Solution?</h3><p>Imagine an array containing <strong>100,000 elements</strong>.</p><p>The brute-force approach checks millions (in fact, billions) of subarrays, making it very slow.</p><p>Can we avoid recalculating sums repeatedly?</p><p>Yes!</p><p>This leads us to <strong>Kadane’s Algorithm</strong>, which solves the problem in a single traversal.</p><h3>Solution 2: Kadane’s Algorithm</h3><h3>Core Idea</h3><p>Instead of checking every possible subarray, we ask one simple question at every element:</p><blockquote><em>Is it better to continue the current subarray, or start a new one from this element?</em></blockquote><p>If the running sum becomes negative, it can only reduce the sum of any future subarray.</p><p>So we discard it and start fresh.</p><h3>Algorithm</h3><p>For every element:</p><ol><li>Add the current element to the running sum.</li><li>Update the maximum sum if needed.</li><li>If the running sum becomes negative, reset it to <strong>0</strong>.</li></ol><p>Repeat until the array ends.</p><h3>Dry Run</h3><p>Array</p><pre>[2, -3, 4, -1, 2, 1, -5, 4]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*a8R6FLxFaRsO-X64QzRCcw.png" /></figure><p>Answer</p><pre>Maximum Sum = 6</pre><p>Subarray</p><pre>[4, -1, 2, 1]</pre><p>Java Code</p><pre>public class KadanesAlgorithm {<br><br>    public static void main(String[] args) {<br><br>        int[] arr = {2, -3, 4, -1, 2, 1, -5, 4};<br><br>        int currentSum = 0;<br>        int maxSum = Integer.MIN_VALUE;<br><br>        for (int num : arr) {<br><br>            currentSum += num;<br><br>            if (currentSum &gt; maxSum) {<br>                maxSum = currentSum;<br>            }<br><br>            if (currentSum &lt; 0) {<br>                currentSum = 0;<br>            }<br>        }<br><br>        System.out.println(&quot;Maximum Sum = &quot; + maxSum);<br>    }<br>}</pre><h3>How Kadane’s Algorithm Works</h3><p>Suppose the running sum becomes:</p><pre>Current Sum = -7</pre><p>The next number is</p><pre>10</pre><p>Two choices exist:</p><p>Continue the previous subarray:</p><pre>-7 + 10 = 3</pre><p>Or start a new subarray:</p><pre>10</pre><p>Clearly,</p><pre>10 &gt; 3</pre><p>So keeping a negative running sum only hurts future sums. That’s why Kadane’s Algorithm resets the running sum to 0 whenever it becomes negative.</p><h4>Complexity Analysis</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*e8AVKsInZTwdqKiouz3rKw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f22030ace0d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular Routing Part 3: Redirect Routes and Wildcard Route (**)]]></title>
            <link>https://medium.com/@varkalerushikesh/angular-routing-part-3-redirect-routes-and-wildcard-route-7d8174e68bfd?source=rss-ea54b0b43ef2------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d8174e68bfd</guid>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[angular-routing]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Rushikesh Anil Varkale ]]></dc:creator>
            <pubDate>Mon, 20 Jul 2026 04:49:26 GMT</pubDate>
            <atom:updated>2026-07-20T04:49:26.123Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. Introduction</h3><p>In the previous article, we learned how to create a default route and highlight the active navigation link using routerLinkActive.</p><p>In this article, we’ll learn two more important routing concepts:</p><ul><li>redirectTo</li><li>Wildcard Route (&#39;**&#39;)</li></ul><p>These help us redirect users to the correct page and display a custom page when they enter an invalid URL.</p><h3>2. What We Will Build</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zK6gpPFsrIMmwzOXrJIIbw.png" /></figure><p>Our application contains:</p><ul><li>Home</li><li>About</li><li>Contact</li><li>Login</li><li>Page Not Found</li></ul><p>We’ll learn:</p><ul><li>Redirect /home to /</li><li>Display a 404 page for invalid URLs</li></ul><h3>3. Create NotFound Component</h3><pre>ng generate component not-found</pre><h3>4. Configure Routes</h3><p><strong>app.routes.ts</strong></p><pre>import { Routes } from &#39;@angular/router&#39;;<br><br>import { HomeComponent } from &#39;./home/home.component&#39;;<br>import { AboutComponent } from &#39;./about/about.component&#39;;<br>import { ContactComponent } from &#39;./contact/contact.component&#39;;<br>import { LoginComponent } from &#39;./login/login.component&#39;;<br>import { NotFoundComponent } from &#39;./not-found/not-found.component&#39;;<br><br>export const routes: Routes = [<br><br>  {<br>    path:&#39;&#39;,<br>    component:HomeComponent<br>  },<br><br>  {<br>    path:&#39;about&#39;,<br>    component:AboutComponent<br>  },<br><br>  {<br>    path:&#39;contact&#39;,<br>    component:ContactComponent<br>  },<br><br>  {<br>    path:&#39;login&#39;,<br>    component:LoginComponent<br>  },<br><br>  {<br>    path:&#39;home&#39;,<br>    redirectTo:&#39;&#39;,<br>    pathMatch:&#39;full&#39;<br>  },<br><br>  {<br>    path:&#39;**&#39;,<br>    component:NotFoundComponent<br>  }<br><br>];</pre><h3>5. What is redirectTo?</h3><p>redirectTo automatically sends users from one route to another.</p><p>Example:</p><pre>{<br>  path:&#39;home&#39;,<br>  redirectTo:&#39;&#39;,<br>  pathMatch:&#39;full&#39;<br>}</pre><p>Now when a user opens</p><pre>/home</pre><p>Angular automatically redirects to</p><pre>/</pre><h3>6. Why do we use pathMatch: &#39;full&#39;?</h3><p>pathMatch tells Angular how to match the URL.</p><p>Example</p><pre>{<br>  path:&#39;home&#39;,<br>  redirectTo:&#39;&#39;,<br>  pathMatch:&#39;full&#39;<br>}</pre><p>full means Angular redirects <strong>only when the complete URL matches</strong> /home.</p><p>Without pathMatch:&#39;full&#39;, Angular may redirect unexpected URLs.</p><h3>7. What is Wildcard Route (&#39;**&#39;)?</h3><p>The wildcard route catches every URL that doesn’t match any defined route.</p><p>Example</p><pre>{<br>  path:&#39;**&#39;,<br>  component:NotFoundComponent<br>}</pre><p>If the user enters</p><pre>/profile</pre><p>or</p><pre>/abc</pre><p>or</p><pre>/xyz123</pre><p>Angular displays the <strong>NotFoundComponent</strong>.</p><h3>8. Create Not Found Page</h3><p><strong>not-found.component.html</strong></p><pre>&lt;h1&gt;404 - Page Not Found&lt;/h1&gt;<br><br>&lt;p&gt;The page you are looking for doesn&#39;t exist.&lt;/p&gt;<br><br>&lt;a routerLink=&quot;&quot;&gt;Go Back Home&lt;/a&gt;</pre><h3>9. Import RouterLink</h3><p><strong>not-found.component.ts</strong></p><pre>import { Component } from &#39;@angular/core&#39;;<br>import { RouterLink } from &#39;@angular/router&#39;;<br><br>@Component({<br>  selector: &#39;app-not-found&#39;,<br>  standalone: true,<br>  imports: [RouterLink],<br>  templateUrl: &#39;./not-found.component.html&#39;,<br>  styleUrl: &#39;./not-found.component.css&#39;<br>})<br>export class NotFoundComponent {<br><br>}</pre><h4>10. Add CSS (Optional)</h4><p><strong>not-found.component.css</strong></p><pre>h1{<br>    color:red;<br>    text-align:center;<br>}<br><br>p{<br>    text-align:center;<br>}<br><br>a{<br>    display:block;<br>    text-align:center;<br>    margin-top:20px;<br>}</pre><h4>11. app.component.html</h4><pre>&lt;nav&gt;<br>  &lt;a routerLink=&quot;/home&quot;&gt;Home&lt;/a&gt;<br>  &lt;a routerLink=&quot;/about&quot;&gt;About&lt;/a&gt;<br>  &lt;a routerLink=&quot;/contact&quot;&gt;Contact&lt;/a&gt;<br>  &lt;a routerLink=&quot;/login&quot;&gt;Login&lt;/a&gt;<br>&lt;/nav&gt;<br><br>&lt;router-outlet&gt;&lt;/router-outlet&gt;</pre><h4>12. app.component.css</h4><pre>/* Navigation Bar */<br>nav {<br>    background-color: #2c3e50;<br>    padding: 15px 20px;<br>    display: flex;<br>    gap: 20px;<br>    border-radius: 8px;<br>}<br><br>/* Links */<br>nav a {<br>    color: white;<br>    text-decoration: none;<br>    font-size: 18px;<br>    font-weight: 500;<br>    padding: 8px 15px;<br>    border-radius: 5px;<br>    transition: 0.3s;<br>}<br><br>/* Hover Effect */<br>nav a:hover {<br>    background-color: #3498db;<br>}</pre><h4>13.app.component.ts</h4><pre>import { Component } from &#39;@angular/core&#39;;<br>import { RouterLink, RouterOutlet } from &#39;@angular/router&#39;;<br><br>@Component({<br>  selector: &#39;app-root&#39;,<br>  standalone: true,<br>  imports: [RouterOutlet,RouterLink],<br>  templateUrl: &#39;./app.component.html&#39;,<br>  styleUrl: &#39;./app.component.css&#39;<br>})<br>export class AppComponent {<br>  title = &#39;my-angular-app6&#39;;<br>}</pre><h4>14. How Routing Works</h4><pre>User Enters URL<br>        │<br>        ▼<br>Angular Checks Routes<br>        │<br>        ├───────────────► Route Found<br>        │                     │<br>        │                     ▼<br>        │            Open Matching Component<br>        │<br>        └───────────────► No Route Found<br>                              │<br>                              ▼<br>                     Wildcard Route (**)<br>                              │<br>                              ▼<br>                    Display Not Found Page</pre><h3>15. Summary</h3><p>In this article, we learned:</p><ul><li>How to redirect one route to another using redirectTo</li><li>Why pathMatch: &#39;full&#39; is required</li><li>How the wildcard route (&#39;**&#39;) catches invalid URLs</li><li>How to create a simple <strong>404 Page Not Found</strong> component</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d8174e68bfd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular Routing Part 6: Route Guards (CanActivate)]]></title>
            <link>https://medium.com/@varkalerushikesh/angular-routing-part-6-route-guards-canactivate-8d13cd3c3460?source=rss-ea54b0b43ef2------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d13cd3c3460</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[route-guards]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[angular-routing]]></category>
            <dc:creator><![CDATA[Rushikesh Anil Varkale ]]></dc:creator>
            <pubDate>Mon, 20 Jul 2026 04:48:50 GMT</pubDate>
            <atom:updated>2026-07-20T04:48:50.807Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. Introduction</h3><p>In the previous article, we learned how to use <strong>Child Routes</strong> to organize related pages under a parent route.</p><p>In this article, we’ll learn about <strong>Route Guards</strong>, specifically the <strong>CanActivate</strong> guard.</p><p>A CanActivate guard is used to <strong>control access to a route</strong>. It checks whether a user is allowed to visit a particular page before Angular loads it.</p><h3>2. What is CanActivate?</h3><p>CanActivate is a route guard that decides whether a route can be activated.</p><p>If it returns:</p><ul><li>true → Navigation is allowed.</li><li>false → Navigation is blocked.</li></ul><p>It is commonly used to protect pages that require the user to be logged in.</p><h3>3. What We Will Build</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GTl_kzBBnnczgkvZrujETQ.png" /></figure><p>We’ll create a simple application with:</p><ul><li>Home Page</li><li>Login Page</li><li>Dashboard Page (Protected)</li></ul><p>Behavior:</p><ul><li>User can open <strong>Home</strong> and <strong>Login</strong>.</li><li>Dashboard is protected.</li><li>If the user is not logged in, Angular redirects them to the Login page.</li></ul><h4>4. Create Components</h4><pre>ng generate component home<br>ng generate component login<br>ng generate component dashboard</pre><h3>5. Create CanActivate Guard</h3><pre>ng generate guard auth</pre><p>Choose:</p><pre>CanActivate</pre><p>Angular creates:</p><pre>auth.guard.ts</pre><h3>6. Create Authentication Service</h3><pre>ng generate service auth</pre><p>auth.service.ts</p><pre>import { Injectable } from &#39;@angular/core&#39;;<br><br>@Injectable({<br>  providedIn: &#39;root&#39;<br>})<br>export class AuthService {<br><br>  isLoggedIn = false;<br><br>}</pre><p>This service stores whether the user is logged in.</p><h3>7. Implement the Guard</h3><p><strong>auth.guard.ts</strong></p><pre>import { inject } from &#39;@angular/core&#39;;<br>import { CanActivateFn, Router } from &#39;@angular/router&#39;;<br>import { AuthService } from &#39;./auth.service&#39;;<br><br>export const authGuard: CanActivateFn = () =&gt; {<br><br>  const auth = inject(AuthService);<br>  const router = inject(Router);<br><br>  if (auth.isLoggedIn) {<br>    return true;<br>  }<br><br>  router.navigate([&#39;/login&#39;]);<br><br>  return false;<br><br>};</pre><h3>Explanation</h3><ul><li>Check if the user is logged in.</li><li>If yes → allow navigation.</li><li>Otherwise → redirect to Login page.</li></ul><h3>8. Configure Routes</h3><p><strong>app.routes.ts</strong></p><pre>import { Routes } from &#39;@angular/router&#39;;<br><br>import { HomeComponent } from &#39;./home/home.component&#39;;<br>import { LoginComponent } from &#39;./login/login.component&#39;;<br>import { DashboardComponent } from &#39;./dashboard/dashboard.component&#39;;<br><br>import { authGuard } from &#39;./auth.guard&#39;;<br><br>export const routes: Routes = [<br><br>  {<br>    path: &#39;&#39;,<br>    component: HomeComponent<br>  },<br><br>  {<br>    path: &#39;login&#39;,<br>    component: LoginComponent<br>  },<br><br>  {<br>    path: &#39;dashboard&#39;,<br>    component: DashboardComponent,<br>    canActivate: [authGuard]<br>  }<br><br>];</pre><h3>Definition</h3><p>The canActivate property tells Angular to execute the guard before opening the route.</p><h3>9. Login Component</h3><p><strong>login.component.ts</strong></p><pre>import { Component } from &#39;@angular/core&#39;;<br>import { Router } from &#39;@angular/router&#39;;<br>import { AuthService } from &#39;../auth.service&#39;;<br><br>@Component({<br>  selector: &#39;app-login&#39;,<br>  standalone: true,<br>  templateUrl: &#39;./login.component.html&#39;<br>})<br>export class LoginComponent {<br><br>  constructor(<br>    private auth: AuthService,<br>    private router: Router<br>  ) {}<br><br>  login() {<br><br>    this.auth.isLoggedIn = true;<br><br>    this.router.navigate([&#39;/dashboard&#39;]);<br><br>  }<br><br>}</pre><h3>10. Login HTML</h3><pre>&lt;h2&gt;Login Page&lt;/h2&gt;<br><br>&lt;button (click)=&quot;login()&quot;&gt;<br>    Login<br>&lt;/button&gt;</pre><h3>11. Dashboard HTML</h3><pre>&lt;h2&gt;Dashboard&lt;/h2&gt;<br><br>&lt;p&gt;Welcome! You have successfully logged in.&lt;/p&gt;</pre><h3>12. App Navigation</h3><p><strong>app.component.html</strong></p><pre>&lt;nav&gt;<br><br>    &lt;a routerLink=&quot;&quot;&gt;Home&lt;/a&gt;<br><br>    &lt;a routerLink=&quot;/login&quot;&gt;Login&lt;/a&gt;<br><br>    &lt;a routerLink=&quot;/dashboard&quot;&gt;Dashboard&lt;/a&gt;<br><br>&lt;/nav&gt;<br><br>&lt;hr&gt;<br><br>&lt;router-outlet&gt;&lt;/router-outlet&gt;</pre><h3>13. Import Required Modules</h3><p><strong>app.component.ts</strong></p><pre>import { Component } from &#39;@angular/core&#39;;<br>import { RouterLink, RouterOutlet } from &#39;@angular/router&#39;;<br><br>@Component({<br>  selector: &#39;app-root&#39;,<br>  standalone: true,<br>  imports: [RouterLink, RouterOutlet],<br>  templateUrl: &#39;./app.component.html&#39;<br>})<br>export class AppComponent {<br><br>}</pre><h3>14. How It Works</h3><h3>Case 1: User is not logged in</h3><p>User opens</p><pre>/dashboard</pre><p>↓</p><p>Guard executes</p><p>↓</p><pre>auth.isLoggedIn</pre><p>↓</p><p>Returns</p><pre>false</pre><p>↓</p><p>Angular redirects to</p><pre>/login</pre><h3>Case 2: User clicks Login</h3><p>↓</p><p>login() method executes</p><p>↓</p><pre>auth.isLoggedIn = true;</pre><p>↓</p><p>Navigate to</p><pre>/dashboard</pre><p>↓</p><p>Guard executes again</p><p>↓</p><p>Returns</p><pre>true</pre><p>↓</p><p>Dashboard opens successfully.</p><h3>15. Flow Diagram</h3><pre>User Opens Dashboard<br>          │<br>          ▼<br>CanActivate Guard Executes<br>          │<br>          ▼<br>Is User Logged In?<br>      │          │<br>     Yes        No<br>      │          │<br>      ▼          ▼<br>Open Dashboard  Redirect to Login</pre><h3>16. Why do we use CanActivate?</h3><ul><li>Protect private pages.</li><li>Prevent unauthorized access.</li><li>Improve application security.</li><li>Control navigation before loading a component.</li></ul><h3>17. Summary</h3><p>In this article, we learned:</p><ul><li>What a Route Guard is.</li><li>What CanActivate does.</li><li>How to create a guard.</li><li>How to protect routes using canActivate.</li><li>How to redirect users to the Login page when they are not authenticated.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d13cd3c3460" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>