Everything failed… but the database still got updated 🙃. Recently, while working on a feature in Spring Boot project, I used @Transactional annotation assuming it would rollback the entire operation if something failed. But during testing, I noticed something strange, even after an exception, some data was still getting saved. That’s when I started digging deeper. I realized that @Transactional doesn’t always behave the way we expect: - It rolls back only for unchecked exceptions (RuntimeException) by default. - If the method call happens within the same class, it might not work due to proxy behavior. - Catching exceptions without rethrowing can prevent rollback. In my case, I was catching the exception and not rethrowing it. So Spring thought everything was fine and committed the transaction. Once I fixed that, the rollback worked as expected. Annotations make things easier… but understanding how they actually work makes you a better developer. #Java #SpringBoot #BackendDevelopment #Transactional #LearningInPublic #SoftwareEngineering #Database #SpringJPA #DataManagement
Transactional Annotation in Spring Boot: Understanding the Gotchas
More Relevant Posts
-
Top 5 mistakes developers make in Spring Boot 🚨 I’ve made some of these myself 👇 ❌ 1. Not using proper exception handling 👉 Leads to messy APIs ❌ 2. Writing fat controllers 👉 Business logic should be in service layer ❌ 3. Ignoring database optimization 👉 Slow queries = slow application ❌ 4. No caching strategy 👉 Repeated DB calls kill performance ❌ 5. Not understanding @Transactional 👉 Can cause data inconsistency 💡 What I learned: Clean architecture + proper layering = scalable system ⚡ Pro Tip: Think like a backend engineer, not just a coder. Which mistake have you made before? 😅 #SpringBoot #Java #CleanCode #BackendDeveloper
To view or add a comment, sign in
-
🔧 3 Things I Always Follow While Building APIs in Spring Boot ✅ 1. Keep Controllers Thin → Only handle request & response — no business logic ✅ 2. Write Clear Service Layer Logic → Keep core logic in services for better maintainability and testing ✅ 3. Optimize Database Queries → Efficient SQL = better performance, especially with large data 💡 Small backend decisions today can save hours of debugging tomorrow. Still learning and improving every day 🚀 What practices do you follow while building APIs? #BackendDeveloper #Java #SpringBoot #RESTAPI #SoftwareEngineering #Tech
To view or add a comment, sign in
-
🌟 Understanding Entity, Repository, and Service Layers in Spring Boot 📌 A well-structured Spring Boot application follows a layered architecture to ensure clean, maintainable, and scalable code. 👉 Entity Layer Represents the database structure. It defines how data is stored using annotations like @Entity and @Id. 👉 Repository Layer Handles database operations. Using Spring Data JPA, it provides built-in methods like save, find, and delete without writing SQL. 👉 Service Layer Contains the business logic of the application. It processes data, applies rules, and connects the controller with the repository. -->A well-structured application using these layers ensures clean code, scalability, and maintainability, which are essential for real-world backend development. #SpringBoot #Java #BackendDevelopment #SoftwareArchitecture #LearningInPublic
To view or add a comment, sign in
-
-
🧬 Mini Project – User API with Spring Boot 🚀 Built my first simple User API using Spring Boot and it gave me a clear understanding of how backend systems work. 🧠 What I implemented: ✔️ POST "/user" → Create a user ✔️ GET "/user/{id}" → Fetch user by ID 💡 Key Concepts Applied: • @RestController, @RequestBody, @PathVariable • JSON request & response handling • Layered architecture: Controller → Service → Data 🔁 Flow: Client → Controller → Service → In-memory data → JSON response 🧪 Tested APIs using Postman and successfully created & retrieved user data. 🚀 Next Steps: • Add validation • Integrate database (MySQL) • Implement exception handling 💻 DSA Practice: • Finding longest word in a sentence • Counting number of words ✨ This mini project helped me connect theory with real backend development. #SpringBoot #Java #BackendDevelopment #RESTAPI #MiniProject #DSA #LearningInPublic #DeveloperJourney
To view or add a comment, sign in
-
💡 How many of us REALLY know how "@Transactional" works in Spring Boot? Most developers use "@Transactional" daily… But under the hood, there’s a lot more happening than just "auto rollback on exception". Let’s break it down 👇 🔹 What is "@Transactional"? It’s a declarative way to manage database transactions in Spring. Instead of manually writing commit/rollback logic, Spring handles it for you. --- 🔍 What actually happens behind the scenes? 1️⃣ Spring creates a proxy object around your service class 2️⃣ When a method annotated with "@Transactional" is called → it goes through the proxy 3️⃣ The proxy: - Opens a transaction before method execution - Commits if everything succeeds ✅ - Rolls back if a runtime exception occurs ❌ --- ⚙️ Execution Flow Client → Proxy → Transaction Manager → Target Method → DB --- 🚨 Important Gotchas ❗ Works only on public methods ❗ Self-invocation (method calling another method inside same class) will NOT trigger transaction ❗ By default, only unchecked exceptions trigger rollback ❗ Uses AOP (Aspect-Oriented Programming) --- 🧠 Advanced Concepts ✔ Propagation (REQUIRED, REQUIRES_NEW, etc.) ✔ Isolation Levels (READ_COMMITTED, SERIALIZABLE) ✔ Transaction Manager (PlatformTransactionManager) ✔ Lazy initialization & session handling --- 🔥 Example @Service public class PaymentService { @Transactional public void processPayment() { debitAccount(); creditAccount(); // If credit fails → debit will rollback automatically } } --- ✨ Pro Tip Understanding "@Transactional" deeply can save you from: - Data inconsistencies - Hidden bugs - Production failures --- 👉 Next time you use "@Transactional", remember — you're not calling a method… you're triggering a proxy-driven transaction lifecycle! #SpringBoot #Java #BackendDevelopment #Microservices #TechDeepDive #Learning
To view or add a comment, sign in
-
-
One thing I have learned while working with Spring Boot applications is that an API can look perfectly fine in development, but production always shows the real behavior. A service may work well with test data and limited traffic, but once real users, larger datasets, and multiple concurrent requests come in, small inefficiencies start becoming very visible. I have noticed that performance issues usually do not come from one major design flaw. Most of the time, they come from small things that slowly add up, like unnecessary database calls, repeated API hits, missing caching, large response payloads, or heavy object mapping. For example, even a simple endpoint that fetches customer or transaction details can become slower than expected when it triggers multiple queries in the background, maps too much data, or sends fields the frontend does not really need. A few areas that make a big difference: 1. Profiling SQL queries instead of assuming the database is fine 2. reducing repeated service calls 3. using proper pagination for large result sets 4. caching frequently accessed data 5. monitoring response times early, not only after issues appear What stands out to me is that backend performance is not just about speed. It is also about reliability. A fast API under light traffic is one thing, but a stable API under load is what really matters. That is one reason I think performance tuning is an important part of backend development. Building APIs is not only about making them work. It is about making them dependable when the system actually starts growing. What is the most common Spring Boot performance issue you have seen in real projects? #SpringBoot #JavaDeveloper #BackendEngineering #PerformanceTuning #Microservices #Java #SoftwareEngineering
To view or add a comment, sign in
-
-
@Transactional is the most used — and most misunderstood — annotation in Spring Boot. Here's what's actually happening when you add it. 🧵 Save this. It will save you from a 2am production incident. ─── WHAT MOST DEVELOPERS THINK ─── "It wraps my method in a database transaction." ─── WHAT IT ACTUALLY DOES ─── Spring creates a proxy around your class at startup. When you call a @Transactional method, you're not calling your class directly you're calling Spring's proxy, which: 1. Opens a database connection 2. Begins a transaction 3. Calls your actual method 4. Commits on success 5. Rolls back on unchecked exception (RuntimeException) 6. Does NOT rollback on checked exceptions by default ─── THE TRAPS NOBODY WARNS YOU ABOUT ─── ⚠ Self-invocation doesn't work If method A() calls @Transactional method B() in the SAME class — the proxy is bypassed. No transaction. Silence. Bugs. ⚠ Default isolation level is READ_COMMITTED Dirty reads are prevented. Phantom reads are not. For financial data, you need SERIALIZABLE. ⚠ Checked exceptions don't trigger rollback new IOException() will NOT rollback your transaction unless you add: @Transactional(rollbackFor = Exception.class) ⚠ Transaction scope matters @Transactional on a public method called from another class = works. @Transactional on a private method = silently ignored. Always. ─── THE RIGHT MENTAL MODEL ─── @Transactional is not magic. It's a proxy. Understand the proxy. Which of these caught you off guard? 👇 #SpringBoot #Java #Transactional #BackendDevelopment #SoftwareEngineering #JavaDeveloper #SpringFramework #Database
To view or add a comment, sign in
-
Over the past few weeks, the focus has been on backend development using Spring as part of the ongoing training. Worked through core concepts including designing the service layer, implementing the persistence layer with Spring Data, and building RESTful APIs, along with an assessment to validate these fundamentals. This phase has provided a clearer understanding of layered architecture, data handling, and how backend services are structured to support scalable applications. Looking forward to applying these concepts in building end-to-end applications and strengthening backend development skills further. #SoftwareEngineering #Java #Spring
To view or add a comment, sign in
-
Clean REST API in Spring Boot (Best Practice) 🚀 Here’s a simple structure you should follow 👇 📁 Controller - Handles HTTP requests 📁 Service - Business logic 📁 Repository - Database interaction Example 👇 @RestController @RequestMapping("/users") public class UserController { @Autowired private UserService userService; @GetMapping("/{id}") public User getUser(@PathVariable Long id) { return userService.getUserById(id); } } 💡 Why this matters: ✔ Clean code ✔ Easy testing ✔ Better scalability ⚠️ Avoid: Putting everything inside controller ❌ Structure matters more than code 🔥 Follow for more practical backend tips 🚀 #SpringBoot #Java #CleanArchitecture #Backend
To view or add a comment, sign in
-
Day 3 – Tech Stack Tech Stack used in my project: Java Spring Boot Spring Data JPA MySQL REST APIs Focused on building a scalable backend system. #TechStack #Backend
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development
Yeah that true brother. To be a good developer, we need to dig down to the roots.