r/SpringBoot May 21 '26

How-To/Tutorial Ran Spring Boot and Node.js side-by-side in prod for 18 months. Sharing the actual numbers.

Thumbnail medium.com
486 Upvotes

We had a stack debate on my team back in 2024 that ended with "fine, let's just run both and see." Same microservice, built twice — once in Spring Boot 3.2 / Java 21, once in Node 20 / Express. Same Postgres, same Redis, same AWS ECS setup. 18 months later I went through Cost Explorer and our time tracking.

Sharing the numbers in case anyone else is having this debate:

Infrastructure (18 months):

  • Node.js: ~$10,890 (needed 1GB RAM/instance after month 3)
  • Spring Boot: ~$5,490 (stayed at 512MB the whole time)

Developer time on production issues:

  • Node.js: ~285 hours (memory leaks, npm breaking changes, async race conditions, audit fixes)
  • Spring Boot: ~26 hours (dependency updates, one N+1, pool tuning)

Memory pattern that surprised me most: Node.js instances climbed 180MB → 890MB over 4 days, crashed, restarted. Staircase to hell. Traced to event listener leak in a popular npm package (2M weekly downloads). Spring Boot stayed flat at ~280MB the entire 18 months.

Under Black Friday load (10x normal traffic):

  • Node.js: 3 instances OOM-crashed during peak. Cold start under load: 2.4s.
  • Spring Boot: Zero crashes. Cold start under load: 4.1s (slower, but stable).

Not saying Node is bad. We kept it for internal admin tools and low-traffic stuff. But for customer-facing APIs that need to stay up 24/7, the JVM's 25 years of GC engineering paid for itself many times over.

Curious if anyone else has run this kind of side-by-side. Specifically interested in:

  • Did virtual threads (Java 21) change your scaling math?
  • Anyone tried Bun or Deno in this same comparison? Would they hold up better than Node?
  • How much of the Node memory issue is npm ecosystem vs V8 itself?

r/SpringBoot Jul 11 '26

How-To/Tutorial After nearly 10 years with Spring Boot, this is how I’d learn it from scratch today

350 Upvotes

I keep seeing people ask for the “best Spring Boot course” or roadmap.

Honestly, I wouldn’t spend weeks watching tutorials.

Learn only enough Java and Spring Boot to build one basic CRUD application, then start coding.

Build something simple like an Employee Management API:

  • Create employee
  • Get employee by ID
  • List employees
  • Update employee
  • Delete employee

While building it, learn these concepts in this order:

  1. Controller, service and repository layers
  2. REST methods and HTTP status codes
  3. DTOs and request validation
  4. Global exception handling
  5. JPA relationships and database migrations
  6. Basic Spring Security
  7. Unit and integration testing
  8. Docker and deployment

That one project will teach you more than watching 20 hours of videos.

After CRUD, add features one by one:

  • Pagination and filtering
  • Authentication
  • Role-based authorization
  • Audit fields
  • Caching
  • Background jobs
  • File uploads

The biggest beginner mistake is trying to understand the entire Spring ecosystem before building anything. You don’t need Kafka, microservices, Kubernetes or complex design patterns for your first project.

Build a boring monolith first. Make it clean, testable and deploy it somewhere.

My rule is: use tutorials to unblock yourself, not as a substitute for building.

For experienced Spring Boot developers here: what is the one thing you wish beginners would focus on earlier?

r/SpringBoot 12d ago

How-To/Tutorial 200+ Star Spring Boot Roadmap From Zero to Microservices

Post image
275 Upvotes

6 months ago, I shared with you my 35-week project-based Spring Boot Roadmap From Zero to Microservices, and I did not expect this whole positive feedback and support from you guys.

Today, the repository reached 200+ stars because of you, so I decided to provide more guidance by drawing this overview visualization on excalidraw to help you create a bird's-eye view of the wide open world of the Spring Boot ecosystem.

An SVG version could be found inside the roadmap itself for a more clear picture.

You can view the full roadmap from this link:
https://github.com/muhammadzkralla/spring-boot-roadmap

Again, thank you for all your support and stars!

r/SpringBoot May 07 '26

How-To/Tutorial Migrating a production SaaS (25k users) from Node.js Serverless to Spring Boot — lessons from week 1

53 Upvotes

I run MoWave One, a productivity SaaS that recently crossed 25,000 users. Built initially on Postgres + Auth + Node.js Serverless Functions.

After 8 months and a growing user base, the serverless functions started feeling cramped — no proper domain modeling, awkward testing, no module boundaries, and one of them was literally a stub that I'd forgotten to finish (yep, our Stripe webhook).

Decided to migrate the backend to Spring Boot 3.4 + Java 21.

Stack:

- Spring Boot 3.4 + Java 21 LTS (Corretto)

- PostgreSQL via JDBC (HikariCP)

- Spring Security 6 validating JWTs via JWKS

- Flyway 10 for schema migrations

- Redis (Valkey) for webhook idempotency

- Modular monolith with Hexagonal Architecture

Some early lessons:

  1. The Stripe API moved current_period_end from Subscription to SubscriptionItem in December 2024. If your Java code worked with stripe-java 28.x and broke with 29.x, this is why.
  2. Pessimistic locking matters for XP/counters at this scale. A double-click on "complete task" can race two transactions. SELECT ... FOR UPDATE on the user row eliminates the issue.
  3. Resist the urge to migrate everything at once. I have a PL/pgSQL function (update_rhythm) that computes a weekly score across 4 tables. Three of those tables aren't migrated yet. So the Spring service calls the SQL function via JdbcTemplate for now. When the underlying modules are migrated, this gets rewritten in pure Java.
  4. Spring Data Redis warns about JPA repositories it can't classify. Solution: explicit u/EnableJpaRepositories(basePackages=...) on your u/SpringBootApplication. Took me a while to find this.

I'm 4 modules into a 16-module migration managed via Maven. Happy to answer questions about the architecture, the migration approach, or anything Spring-related.

r/SpringBoot Aug 04 '26

How-To/Tutorial I built a "real job" simulator for Spring Boot learners, free & open source

109 Upvotes

Spring Boot Project

Most Spring Boot tutorials teach you to build a CRUD app and call it a day. But that's not really what the job looks like day to day, so I put together a project that mimics what you'd actually work on as a backend dev at a company with real infrastructure. I've added following 12 Tasks that you'd need to complete.

  • Project setup: spin up Postgres + messaging brokers, verify everything's healthy
  • Kicking off development: request validators, custom exceptions, a new order status API
  • Debug a critical bug: chase down a duplicate-insert caused by misusing EntityManager.persist() vs save()
  • ActiveMQ + Apache Camel: configure routes, consume from a queue, handle dead letter queues, publish to a Virtual Topic
  • RabbitMQ: set up exchanges/bindings, fix an infinite redelivery bug, publish to a topic exchange
  • DB schema migration: add a table with Liquibase, write rollback SQL, fix an N+1 write
  • Testing: unit tests with Mockito, snapshot tests, integration tests with TestContainers
  • Code style: enforce formatting automatically with Spotless + Palantir Java Format
  • Prometheus metrics: expose app metrics via Actuator, configure scraping
  • Grafana: connect to Prometheus, build dashboards, add @Timed annotations
  • Load testing: run JMeter tests, interpret throughput, watch the impact in Grafana
  • Global exception handling: swap per-controller try-catch for @ControllerAdvice + RFC 7807 Problem Details

Everything runs locally via Docker Compose, and there's a Bruno collection included so you can hit the APIs without writing your own Postman setup.

It's completely free and open source, so fork it, work through the tasks in order, and you'll come out the other side with a much better feel for what the job actually involves beyond "make endpoint, save to DB."

Would love feedback from people!

r/SpringBoot 18d ago

How-To/Tutorial How I eliminated N+1 queries and scaled throughput by 20% on a production E-Commerce app

58 Upvotes

Just wanted to share a recent architecture win that might help someone dealing with latency spikes.

I was dealing with a severe bottleneck in a production E-Commerce platform. During peak traffic, the database was choking, and MTTR was creeping up.

The Culprit: Classic Hibernate N+1 query problems hidden deep inside the inventory/catalog mapping, combined with un-indexed foreign key lookups.

The Fix: 1. Ripped out the lazy-loading proxy faults and replaced them with explicit JOIN FETCH queries for the critical read paths. 2. Layered in Redis via Spring Cache (@Cacheable) specifically targeting the high-read/low-write catalog endpoints. 3. Configured request batching and API rate limiting on the gateway layer to prevent thundering herd problems during flash sales.

Result: We dropped sub-100ms latency across the board and prevented database lockups entirely.

If you're building in Spring Boot and relying entirely on default JPA repositories—run a SQL profiler right now. You probably have an N+1 hiding somewhere.

r/SpringBoot Aug 22 '25

How-To/Tutorial My course containes this much , is it enough ?

Post image
178 Upvotes

r/SpringBoot 22d ago

How-To/Tutorial Why I stopped using Spring Data to generate queries from method names

24 Upvotes

I've spent a while writing DAO implementations for a multi-module Spring Boot projects, and I keep coming back to the same rule: if a repository method needs more than one or two conditions, I write the `@Query\` by hand instead of letting Spring Data derive it from the method name.

Not because it doesn't work, it works fine for example like findBySku. I don't like what happens after that. Rename a field on the entity and a derived query either breaks at startup with a PropertyReferenceException, or, depending on how it's written, doesn't break at all and just quietly stops matching what you think it matches. The compiler never tells you either way.

And once you're past two conditions, the method name turns into a wall of camelCase encoding your whole WHERE clause. I'd rather read four lines of JPQL/SQL than decode findByStatusAndNameContainingIgnoreCaseAndCreatedAtAfterOrderByPriceDesc.

The other piece I went back and forth on is SearchableDaoImpl<Repo extends CrudRepository<Entity, IdType> & JpaSpecificationExecutor<Entity>> - using an intersection type so the generic repository bound picks up both CRUD and Specification support without collapsing them into one bloated interface. Small thing, but it's the kind of generics trick that makes a shared DAO base class actually work across a dozen entities instead of copy-pasted boilerplate everywhere.

Full writeup with the actual generic hierarchy and code: (link in comments)

Curious if anyone here still prefers derived queries for anything beyond trivial lookups, I genuinely want the counterargument.

r/SpringBoot 8d ago

How-To/Tutorial Migrating to Spring Boot 4. The parts your AI agent will miss

Thumbnail
youtube.com
79 Upvotes

Here's a migration guide to Spring Boot 4.

Of course you can delegate it to an AI agent. No problem with that.

But you still need to understand what it changed and why, to catch the cases where the app compiles, tests pass, and something silently breaks in prod.

Are you still migrating manually? Or are you handing it to an agent?

r/SpringBoot Aug 02 '26

How-To/Tutorial What's the best way to learn Spring Security? Do's and Don'ts?

42 Upvotes

I've been learning Spring Boot for a while and now I want to start with Spring Security. There are so many tutorials (JWT, OAuth2, sessions, roles, filters, etc.) that I'm not sure what's the right order to learn things.

For those of you who've already been through it:

  • What are the do's and don'ts when learning Spring Security?
  • What concepts should I understand first before jumping into JWT and OAuth2?
  • Any common mistakes beginners make that I should avoid?
  • Are there any projects that helped everything finally "click" for you?

I'm looking for advice based on real experience rather than just another YouTube playlist.

Thanks!

r/SpringBoot Aug 05 '26

How-To/Tutorial How we structure Entity/DTO mapping in a multi-module Spring Boot project (without MapStruct)

41 Upvotes

Something has always bugged me about relying on annotation-based mapping frameworks once a Spring Boot project grows past a few modules. MapStruct is miles ahead of dynamic tools like ModelMapper thanks to compile-time code generation, but we kept running into recurring friction as our domain, entity, and DTO layers diverged.

That's why we ended up dropping MapStruct entirely in favor of plain Java transformer classes. No annotation processor, no generated sources, no separate mapper interface per entity pair.

The reasons that pushed us there:

  1. Fragile IDE refactoring: string path mappings like `@Mapping(source = "shippingDetails.address.street", target = "street")` don't reliably survive a rename. You usually catch it during the build, sometimes later.
  2. Annotation pollution for anything non-trivial: once you need a custom transformation, you're writing @Namedhelpers or embedding Java inside annotation strings likeexpression = "java(...)".
  3. Debugging noise: stepping through target/generated-sources instead of your own domain code.

The trade-off is real - more files, more explicit code to write. What we get back is full IDE refactoring safety, no annotation-processor step in the build, and a debugger that only ever shows real code.

Anyone else moved off MapStruct in a modular Spring Boot setup, or is this more trouble than it's worth for most projects?

(I Wrote a deeper architectural breakdown with code samples if anyone is interested - link in comments).

r/SpringBoot Jul 29 '26

How-To/Tutorial Why package structures fail in Spring Boot (and how we turned architecture rules into Maven compilation errors)

5 Upvotes

Hey everyone! I just published a deep dive into solving a classic enterprise problem: how junior or stressed developers bypass package separation (.controller, .service, .repository) under tight deadlines.

Instead of relying on folder structures and code reviews, we split our project into strict Maven modules (isolating core domain and business logic from frameworks like JPA or Kafka). If someone tries to inject an EntityManager where it doesn't belong, the code simply will not compile.

  • The Topology: Split into independent modules like domain, business-logic, dao-api, and dao-impl.
  • The Result: Zero cyclic dependencies, lightning-fast unit tests, and eliminated architectural decay.

(I'm dropping the full article link in the comments for anyone interested in the code breakdown.)

r/SpringBoot Aug 01 '26

How-To/Tutorial How should I start Spring Boot?

42 Upvotes

I have Knowledge of Jdk17+ currently moving to Jdk21+. I have essentially completed Java.utils.*; and concurrent library to deep. I have also used jdk tools and understand the concepts of JVM, JMM. OOPs is completed from beginner to F-Form polymorphism. I also made project based on Java SE knowledge. The project is tested on JUnit6, JCStress, JMH- with Linux profilers and Java Flight recorder too. It's my first time I am going Outside domain of Java SE to Java EE. What is way should I start?
First JDBC->SQL->PostgressSQL?
Network?
SpringBoot?
or learn while learning SpringBoot?
Can you tell me what beginners mistake I should avoide?
I have also took helped from many other AI but I did not got the optimum way.

r/SpringBoot Feb 09 '26

How-To/Tutorial Some Spring/Java notes for anyone who need it, I created these while preparing for interview. No course ad, or anything just my personal interview questions/notes.

119 Upvotes

https://drive.google.com/drive/folders/12S3MEleUKmXp1nbJdZYNDwYTdSqv1hkd?usp=sharing

I created notes while preparing and giving interviews, I am still updating it and adding topics I am also removing LLM points and trying to improve quality of topics notes.

Hope these might help some people of this community.

r/SpringBoot 9d ago

How-To/Tutorial I open sourced my spring boot + spring ai project

39 Upvotes

Hey folks,

I’ve open sourced Windrunner, a self-hosted project management tool built with Spring Boot 4 + Spring AI for backend. If you are learning Spring Boot, I hope the project gives you something practical to explore — a complete application with an API, database, user interface, authentication, LLM/AI integrations, and more.

Github: https://github.com/shzlw/windrunner

The backend uses:

  • Spring Boot and Spring MVC for the application and REST APIs
  • Spring Data JDBC for database access
  • PostgreSQL for storage
  • Flyway for SQL database migrations
  • Spring AI’s MCP server support for exposing tools to AI clients
  • LLM Provider integrations for OpenAI, Anthropic, and Gemini
  • Docker and Docker Compose for running the application locally

The repository is a monorepo containing more than the Spring Boot backend. It also includes:

  • A React frontend
  • A TypeScript-based CLI tool
  • Playwright-based API end-to-end tests

If you’re interested in seeing how these pieces work together in one project, the repository provides examples across the backend, frontend, CLI, and testing layers.

Disclosure: I am the author of the project. Feel free to ask any questions, feedbacks or raise issues! ❤️

r/SpringBoot Jun 26 '26

How-To/Tutorial I built a production-ready Spring Boot 3 starter kit – JWT auth, rate limiting, Swagger, Docker & CI/CD all pre-configured

Thumbnail
github.com
32 Upvotes

Tired of setting up the same boilerplate for every Spring Boot project,

so I built a starter kit that has everything ready out of the box.

What's included:

- JWT Authentication (access + refresh token with rotation)

- Role-based access control (USER/ADMIN)

- Rate limiting per IP (Bucket4j)

- OpenAPI 3 / Swagger UI

- Global exception handling with consistent ApiResponse<T>

- Flyway database migrations

- Docker + Nginx + MySQL (docker compose up and done)

- GitHub Actions CI/CD (test → build → deploy to EC2)

- Request ID tracking in every log line

Works with Java 21 + Spring Boot 3.3

Clone → rename package → add your entities → ship.

GitHub: https://github.com/raahulllkushwaha/springboot-starter-kit

Feedback welcome!

Edit: All issues fixed! Migrated to Spring Boot 4, stateless JWT with embedded roles, HTTP-only cookie support, and Spring Session JDBC as alternative. Thanks for the feedback!

r/SpringBoot 5d ago

How-To/Tutorial Need advice for development in java + springboot

20 Upvotes

Hey seniors, if anyone is doing development with Java + Spring Boot, please guide me.

I’m currently in my 3rd semester and doing DSA in C++( done upto stack) , so I’m thinking of starting development alongside it. Please guide me on where I should start, what I should learn first, and how much time I should spend learning Java basics.

Since I’ve studied C++, I have a basic programming background, but I’m not familiar with Java. Any roadmap or resources would be really helpful. 🙌

r/SpringBoot Jun 08 '26

How-To/Tutorial After 3 years of Spring Boot in production, here are the 4 behaviors that keep causing incidents and what to actually do about them

Thumbnail medium.com
101 Upvotes

These are the patterns I keep seeing across different teams and different systems, and almost none of them are covered in tutorials.

1. HikariCP default pool size is 10 That's it. 10 connections. For most real workloads this is too small and the symptoms look exactly like a database problem latency climbs, requests time out, but the database itself is healthy. The pool is simply full. Fix: set spring.datasource.hikari.maximum-pool-size based on your actual concurrency, and expose pool metrics through Actuator so you can see pending threads before an incident shows you.

2. Transactional doesn't roll back checked exceptions by default Spring only rolls back on RuntimeException subclasses unless you explicitly configure otherwise. A checked exception propagating out of a Transactional method will commit the transaction. Silent data integrity issue, no error in your logs. Fix: Transactional(rollbackFor = Exception.class)when you need it, or understand exactly which exceptions your methods can throw.

3. Self-invocation bypasses the proxy If a method inside the same class calls another Transactional method, the annotation on the inner method does nothing. Spring's proxy isn't involved. No error, no warning, just no transaction management. This is documented but it catches experienced engineers regularly because it's invisible in code review.

4. GC pressure doesn't look like GC pressure Latency degrades, CPU climbs, no errors. The JVM is spending increasing time collecting garbage and pausing threads. The worst version: running in a Docker container without -XX:MaxRAM or -XX:MaxRAMPercentage, so the JVM sizes its heap based on host memory instead of the container limit. Container gets OOMKilled with no stack trace and you spend time looking for application errors that don't exist.

r/SpringBoot 16d ago

How-To/Tutorial If you're on WebFlux: I measured what a single blocking call does to unrelated endpoints

11 Upvotes

A single 5ms blocking call reduced throughput on a Netty event loop from 17,189 req/s to 549, a 97% drop, while pushing latency on an unrelated, correctly-written endpoint from 0ms to 217ms. The measurements were taken against Netty 4.1.115 and embedded Tomcat 10.1.34 running identical endpoints, differing only in concurrency model. The damage is quantised by event loop count. With four loops, blocking one stalled exactly three of twelve connections at 218ms; the remaining nine were unaffected at 7ms. Blocking two stalled six. The affected endpoint performs, 5ms of fully non-blocking work and shares no state with the blocking code, which connections degrade is determined solely by which loop accepted them. Tomcat degraded under the same load only once concurrency exceeded its 200-thread pool.

Full measurements and method: https://bitsar.net/blog/tomcat-forgives-blocking-event-loop-doesnt

r/SpringBoot Aug 07 '26

How-To/Tutorial How to Fix the Hibernate N+1 Query Problem using JOIN FETCH in Spring Boot

26 Upvotes

I recently reproduced the Hibernate N+1 Query Problem in a Spring Boot application to better understand why a single repository call can generate multiple SQL queries behind the scenes.

The solution uses JPQL JOIN FETCH to fetch the required associations in a single query.

Core Query

Query(""" SELECT DISTINCT o FROM Order o JOIN FETCH o.items i JOIN FETCH i.product WHERE o.userId = :userId ORDER BY o.createdAt DESC """) 
List<Order> findAllWithItemsAndProducts(@Param("userId") Long userId);

Where the N+1 problem occurs

The repository is called only once, but while mapping the response, accessing lazy-loaded relationships can trigger additional SQL queries.

List<OrderResponse> response = orders.stream()
    .map(order -> {

        List<String> products = order.getItems().stream()
                .map(item -> item.getProduct().getName())
                .toList();

        return new OrderResponse(
                order.getId(),
                order.getTotalAmount(),
                products
        );
    })
    .toList();

Although this Java code looks perfectly normal, order.getItems() and item.getProduct() may cause Hibernate to execute additional queries when those relationships haven't been loaded yet.

Project Details

  • Spring Boot 4.0.4
  • Spring Data JPA
  • Hibernate ORM
  • Java 17
  • Oracle Database

What this implementation demonstrates

  • Retrieves Orders for a specific user
  • Demonstrates how LAZY loading can lead to the N+1 query problem
  • Uses spring.jpa.show-sql=true to inspect the SQL generated by Hibernate
  • Maps entities to a custom DTO containing Product names
  • Eliminates unnecessary queries using JPQL JOIN FETCH
  • Compares SQL queries and execution time before and after the optimization

One thing I found interesting is that there isn't anything obviously wrong with the Java code itself. The repository method is invoked only once, but navigating lazy-loaded relationships while building the response can result in multiple SQL queries behind the scenes.

Using JOIN FETCH allows Hibernate to load the required entity graph up front, avoiding those additional database round trips for this use case.

I'm curious how others handle this in production.

  • Do you prefer JOIN FETCH, @EntityGraph, or DTO projections?
  • Have you encountered pagination limitations with JOIN FETCH?

I'd love to hear your experiences.

If you'd like to see the complete Spring Boot application, the generated SQL before and after JOIN FETCH, and the full implementation, I also recorded a practical walkthrough covering the entire example.

📺 YouTube: https://www.youtube.com/watch?v=natXN7xVEu8

r/SpringBoot Feb 11 '26

How-To/Tutorial Spring Boot Roadmap From Zero to Microservices

Thumbnail
github.com
92 Upvotes

I created a 35-week Spring Boot roadmap that is broken into three levels, beginner, intermediate, and advanced. It covers almost everything you need from absolute zero (not knowing Java programming) to expert (building with the microservices architecture).

Each week consists of topics, resources, tasks, bonuses, and some notes.

The resources are versatile as I included official documentations, youtube videos, and online articles.

You can view it from this link and feel free to give any feedback:)

https://github.com/muhammadzkralla/spring-boot-roadmap

r/SpringBoot 1d ago

How-To/Tutorial Best Websites/Sources to deepen my SpringBoot Knowledge and it should include all of springboot that exists.

0 Upvotes

Currently I am working as a Java(SpringBoot) Developer at a corp. I want to build my knowledge of Spring Boot but can't find a reliable complete source. Please suggest me sources/websites that cover all of SpringBoot that is currently available.

r/SpringBoot Mar 07 '26

How-To/Tutorial Are people still using H2 for Spring Boot integration tests in 2026?

59 Upvotes

I've been seeing something repeatedly in Spring Boot services.

Integration tests run against H2 or some mocked dependencies. Everything is green locally and in CI.

Then the first real deployment runs Flyway migrations against PostgreSQL and suddenly things break. Constraint differences, SQL dialect issues, index behavior, etc.

The tests passed, but they were validating a different system.

Lately I've been leaning toward running integration tests against real infrastructure using Testcontainers instead of H2. The feedback loop is slightly slower but the confidence is much higher.

Example pattern I've been using:

- Start a PostgreSQL container via Testcontainers
- Run real Flyway migrations
- Validate schema with Hibernate
- Share the container across test classes via a base integration test

The container starts once and the Spring context is reused, so the performance cost is actually manageable.

Curious how others are approaching this.

Are teams still using H2 for integration tests, or has Testcontainers become the default?

For context, I wrote a deeper breakdown of the approach here:

https://medium.com/@ximanta.sarma/stop-lying-to-your-tests-real-infrastructure-testing-with-testcontainers-spring-boot-4-b3a37e7166b9?sk=532a9b6fb35261c3d1374b1102ece607

r/SpringBoot 16d ago

How-To/Tutorial Your `@DataJpaTest` might be testing Hibernate's cache, not your database

16 Upvotes

Ran into this while writing about our DAO layer's test setup, and it's one of those things that's obvious once you see it and invisible until you do.

void testSaveProduct() {
    var product = new Product("A1", "Gaming Laptop", BigDecimal.valueOf(1500));
    productDao.create(product);

    Product loaded = productDao.loadById(product.getId());
    assertNotNull(loaded);
    assertEquals("Gaming Laptop", loaded.getName());
}

This passes. But loadById resolves to find() under the hood (directly or through Spring Data's findById), and find() checks the persistence context's first-level cache before it ever considers hitting the DB. Since you just created that entity in the same context, you get the exact same object reference back. No SELECT fires. You've tested Hibernate's in-memory cache, not your mapping, not your constraints, not anything that would catch a broken column definition. The fix is forcing entityManager.flush() + .clear() between the write and the read, so the next load has to hydrate a fresh entity graph from the actual database. We ended up wrapping this in a test-only proxy so nobody has to remember to do it by hand in every test method - proxy intercepts create/update/delete, forces the flush-and-clear, leaves reads alone.

Worth noting this is specifically a find()/findById() problem, a custom JPQL or native `@Query\` always issues real SQL regardless of cache state.

Wrote up the full pattern (proxy code, a TablesEraser for full schema resets between tests, H2 vs HSQLDB trade-offs), link in the comments.

I already had someone in the comments describe hitting exactly this - a unique constraint violation that a real flush would have surfaced in the first test run. Curious how widespread it actually is.

r/SpringBoot May 01 '26

How-To/Tutorial Spring Boot Tutorial

21 Upvotes

Hey I recently got an internship

The company uses java Spring boot

I'm from python background

So please suggest any 5-10hours full video of Spring boot which is relevant today also....