<?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 somil jain on Medium]]></title>
        <description><![CDATA[Stories by somil jain on Medium]]></description>
        <link>https://medium.com/@somil16022006?source=rss-fa54ab34a6d9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*h3OrY4SgMp1XANIn</url>
            <title>Stories by somil jain on Medium</title>
            <link>https://medium.com/@somil16022006?source=rss-fa54ab34a6d9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 17:56:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@somil16022006/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[Why Spring Data JPA is Slow for Batch Operations?]]></title>
            <link>https://medium.com/@somil16022006/why-spring-data-jpa-is-slow-for-batch-operations-417abf4a496d?source=rss-fa54ab34a6d9------2</link>
            <guid isPermaLink="false">https://medium.com/p/417abf4a496d</guid>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[spring-data-jpa]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[somil jain]]></dc:creator>
            <pubDate>Mon, 06 Apr 2026 09:20:03 GMT</pubDate>
            <atom:updated>2026-04-06T09:20:03.006Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/315/0*OCeoPjVHEiExii10" /></figure><p>You have a standard Spring Boot application, and everything is blazing fast until you need to insert or update 100,000 records. You instinctively reach for saveAll(), fire up the application, and watch as your heap usage climbs and processing times stretch into a major performance bottleneck.</p><p><strong>JPA (Java Persistence API)</strong> is a <strong>Java specification</strong> for managing relational data. Think of it as a <em>set of rules/interfaces</em> that define how Java objects should be stored and retrieved from a database.</p><p><strong>Spring Data JPA</strong> is a <strong>Spring abstraction layer on top of JPA. </strong>It removes boilerplate and makes working with JPA much easier.</p><p><strong>Batch operations</strong> are when you process <strong>a large number of records together in chunks (batches)</strong> instead of handling them one-by-one.</p><p>Example:-</p><p>Instead of doing this (one-by-one):</p><pre>for (User u : users) {<br>    save(u); // 100,000 separate DB calls<br>}</pre><p>You do this (in batches):</p><pre>saveAll(users);</pre><p>Spring Data JPA is fantastic for building CRUD-based applications quickly. It abstracts away boilerplate, manages entities, and aligns beautifully with domain-driven design. However, there’s a fundamental limitation:</p><p>JPA is optimized for OLTP (transactional operations), not bulk data processing. So when it comes to <strong>batch operations (10K–1M+ records)</strong>, things start to fall apart. Let’s break down <em>why</em> this happens,</p><p><strong>1: Persistence Context (First-Level Cache)</strong></p><p><strong>Persistence Context</strong> is basically a <strong>memory space managed by JPA</strong> where all your entities are stored and tracked during a transaction. JPA keeps <strong>every managed entity in memory</strong> inside the Persistence Context.</p><p>So if you insert 100,000 rows:</p><ul><li>100,000 Java objects stay in memory</li><li>Memory usage grows rapidly</li><li>Performance degrades over time</li></ul><p>Unless you explicitly clear it, nothing is released.</p><p><strong>2: Dirty Checking on Updates</strong></p><p>JPA doesn’t just update data, it <em>tracks changes</em>. For every update, it:</p><ol><li>Loads the entity</li><li>Tracks changes</li><li>Compares old vs new state</li><li>Generates SQL</li></ol><p>This is efficient but expensive. Especially when you just want to run a simple bulk update.]</p><p><strong>3: </strong><strong>saveAll() is Misleading</strong></p><p>saveAll() sounds like batching, but it isn’t.</p><p>When we call</p><pre>saveAll(list);</pre><p>Internally, it behaves like:</p><pre>for (Entity e : list) {<br>    save(e);<br>}</pre><ul><li>No guaranteed batching</li><li>Just repeated single inserts</li></ul><p><strong>4: ID Generation Strategy Kills Batching</strong></p><p>If you’re using:</p><pre>@GeneratedValue(strategy = GenerationType.IDENTITY)</pre><p>Hibernate <strong>disables batching</strong>.</p><p>Why?</p><ul><li>The database must return the ID immediately</li><li>Each insert must execute instantly</li><li>No grouping, No batching</li></ul><p><strong>5: </strong><strong>flush() Timing is Deceptive</strong></p><p>flush() is the operation that <strong>synchronizes the Persistence Context with the database</strong>.</p><p>Even if you enable batching, Hibernate may delay execution and only send the SQL at flush time. If you don’t manage your flushes during a massive batch operation, memory continues to grow, and your configured batching becomes completely ineffective.</p><p><strong>6: Cascading Makes It Worse</strong></p><pre>@OneToMany(cascade = CascadeType.ALL)</pre><p>During batch inserts:</p><ul><li>Hibernate walks the entire object graph</li><li>Persists related entities</li><li>Increases SQL count and memory usage</li></ul><p><strong>7: N+1 Problem During Updates</strong></p><p>This pattern is dangerous:</p><pre>findAll()<br>→ loop<br>→ update</pre><p>Leads to:</p><ul><li>N+1 queries</li><li>Lazy loading overhead</li><li>Massive performance hit</li></ul><p><strong>8: Hibernate Uses Row-by-Row INSERT by Default</strong></p><p>Even with batching enabled:</p><ul><li>SQL is built per entity</li><li>Sent individually unless configured properly</li></ul><p>To avoid this:</p><pre>spring.jpa.properties.hibernate.jdbc.batch_size=50<br>spring.jpa.properties.hibernate.order_inserts=true<br>spring.jpa.properties.hibernate.order_updates=true</pre><p><strong>9: Massive Garbage Collection (GC) Pauses</strong></p><p>Processing 100,000 records means:</p><ul><li>100K entity objects</li><li>Thousands of internal Hibernate structures</li><li>Rapid heap growth</li></ul><p>This results in <strong>Stop-the-world GC pauses.</strong></p><p><strong>10: Transaction Size Explosion</strong></p><p>When we use,</p><pre>@Transactional</pre><p>It leads to:</p><ul><li>Long-running locks</li><li>Increased rollback cost</li><li>DB contention</li><li>Huge undo logs</li></ul><p>If it fails at 99%, everything rolls back</p><h3><strong>How to Handle Batch Operations Efficiently</strong></h3><ol><li><strong>Use JDBC batching properly</strong></li></ol><pre>for (int i = 0; i &lt; users.size(); i++) {<br>    entityManager.persist(users.get(i));<br><br>    if (i % 50 == 0) {<br>        entityManager.flush();<br>        entityManager.clear();<br>    }<br>}</pre><p><strong>2. Avoid IDENTITY strategy</strong></p><pre>@GeneratedValue(strategy = GenerationType.SEQUENCE)</pre><p><strong>3. Use bulk queries for updates</strong></p><pre>@Modifying<br>@Query(&quot;UPDATE User u SET u.status = :status&quot;)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=417abf4a496d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>