🔹 Spring Tip: Where to Put @Transactional Many developers wonder: Should @Transactional go on repositories or service methods? Service Layer ✅ @Service public class UserService { @Transactional public void transferMoney(...) { ... } } Wraps multiple repository calls in one atomic transaction Ensures business logic consistency Supports propagation, isolation, read-only flags, rollback rules Repository Layer ❌ (usually) @Repository public interface UserRepository extends JpaRepository<User, Long> { @Transactional Optional<User> findById(Long id); } Each call starts its own transaction Adds overhead: dirty checking, flush, commit/rollback Breaks atomicity if multiple repo calls are made separately 💡 Best practice: Annotate service methods, not repositories. Use @Transactional(readOnly = true) for read-only queries. Profile first — small changes can give huge performance gains. #SpringBoot #Java #BackendEngineering #Transactions #JPA #Performance #SpringTips
Where to Put @Transactional in Spring Boot
More Relevant Posts
-
Sravan Nalajala, Great statement 👍 Just to support what you’ve mentioned, * Repository methods in Spring Data are automatically transactional, so there’s no need to explicitly mark them with @Transactional in most cases. * But, the moment you move outside the repository layer. For example, to a service layer, a class/method that orchestrates multiple repository calls, Spring won’t automatically make that method transactional. You should explicitly use @Transactional at this level to ensure all operations participate in a single, consistent transaction. Spring team designed repository CRUD methods to be transactional by nature in order to guarantee correctness, consistency, and compliance with the JPA specification. If you’d like to explore this topic further, here’s a good read: https://lnkd.in/ea4BBSSF
Experienced Software Engineer with Proficiency in Java | SpringBoot | GCP | Microservices | Scala | AWS | RAG | AI | ML
🔹 Spring Tip: Where to Put @Transactional Many developers wonder: Should @Transactional go on repositories or service methods? Service Layer ✅ @Service public class UserService { @Transactional public void transferMoney(...) { ... } } Wraps multiple repository calls in one atomic transaction Ensures business logic consistency Supports propagation, isolation, read-only flags, rollback rules Repository Layer ❌ (usually) @Repository public interface UserRepository extends JpaRepository<User, Long> { @Transactional Optional<User> findById(Long id); } Each call starts its own transaction Adds overhead: dirty checking, flush, commit/rollback Breaks atomicity if multiple repo calls are made separately 💡 Best practice: Annotate service methods, not repositories. Use @Transactional(readOnly = true) for read-only queries. Profile first — small changes can give huge performance gains. #SpringBoot #Java #BackendEngineering #Transactions #JPA #Performance #SpringTips
To view or add a comment, sign in
-
💡 Day 8 of my 𝗝𝗮𝘃𝗮 𝗕𝗮𝗰𝗸𝗲𝗻𝗱 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻 𝗼𝗳 𝘁𝗵𝗲 𝗗𝗮𝘆 𝘀𝗲𝗿𝗶𝗲𝘀: 🧠 Question: In large Spring Boot applications, object creation and dependency management can become complex. Which Design Pattern helps manage object creation efficiently, and how does Spring leverage it? ✅ Answer: The Factory Design Pattern helps centralize and simplify object creation - instead of instantiating classes directly using new, we delegate this responsibility to a factory. 𝐈𝐧 𝐒𝐩𝐫𝐢𝐧𝐠 𝐅𝐫𝐚𝐦𝐞𝐰𝐨𝐫𝐤: Spring uses the Factory pattern through its IoC Container (ApplicationContext). It acts as a Bean Factory, managing object creation, dependency injection, and lifecycle automatically. 𝐞𝐱𝐚𝐦𝐩𝐥𝐞: You define beans in configuration or annotations like @Component, and Spring’s ApplicationContext (the factory) creates and wires them when needed. 𝐛𝐞𝐧𝐞𝐟𝐢𝐭𝐬: • Loose coupling between components • Easier testing and maintenance • Centralized control of object lifecycle ✅ Factory Pattern = clean, modular, and dependency-managed applications - the core of Spring’s IoC. ⚙️ See you tomorrow for Day 9 👋 #Java #SpringBoot #DesignPatterns #FactoryPattern #IoC #BackendDeveloper #CleanCode #ContinuousLearning #QuestionOfTheDay
To view or add a comment, sign in
-
𝘽𝙚𝙖𝙣 𝙎𝙘𝙤𝙥𝙚𝙨: @𝙎𝙞𝙣𝙜𝙡𝙚𝙩𝙤𝙣 𝙫𝙨. @𝙋𝙧𝙤𝙩𝙤𝙩𝙮𝙥𝙚—𝙒𝙝𝙮 𝙄𝙩 𝙈𝙖𝙩𝙩𝙚𝙧𝙨 𝙞𝙣 𝙈𝙞𝙘𝙧𝙤𝙨𝙚𝙧𝙫𝙞𝙘𝙚𝙨 𝗠𝗲𝘁𝗿𝗶𝗰: Incorrect bean scope usage is a leading cause of memory leaks in Spring microservices, often resulting in stale session data piling up and increased memory consumption. 𝗣𝗿𝗼𝗯𝗹𝗲𝗺: Many developers default to @Singleton for all services, causing unwanted shared state across requests and users, which leads to memory leaks and performance issues. 𝗧𝗵𝗲 𝗕𝘂𝗴: // ❌ WRONG: Stateful service as singleton (default) @Service public class UserSessionService { private Map<String, SessionData> sessionMap = new HashMap<>(); // Shared across all requests and users — leads to state leakage! } 𝗧𝗵𝗲 𝗙𝗶𝘅: // ✅ CORRECT: Use @Prototype for stateful beans @Service @Scope("prototype") public class UserSessionService { private Map<String, SessionData> sessionMap = new HashMap<>(); // New instance per request prevents cross-user leakage } 𝙊𝙧 𝙚𝙫𝙚𝙣 𝙗𝙚𝙩𝙩𝙚𝙧, 𝙧𝙚𝙛𝙖𝙘𝙩𝙤𝙧 𝙩𝙤𝙬𝙖𝙧𝙙𝙨 𝙨𝙩𝙖𝙩𝙚𝙡𝙚𝙨𝙨 𝙙𝙚𝙨𝙞𝙜𝙣 𝙬𝙝𝙚𝙣𝙚𝙫𝙚𝙧 𝙥𝙤𝙨𝙨𝙞𝙗𝙡𝙚 𝙛𝙤𝙧 𝙤𝙥𝙩𝙞𝙢𝙖𝙡 𝙨𝙘𝙖𝙡𝙖𝙗𝙞𝙡𝙞𝙩𝙮. 𝗥𝗲𝗮𝗹 𝗜𝗺𝗽𝗮𝗰𝘁: After one incident, I found 15,000 stale sessions accumulating in production memory due to accidental state retention in a singleton. Switching to prototype scope and stateless beans cut memory use by up to 70%. 𝗖𝗮𝗹𝗹-𝘁𝗼-𝗔𝗰𝘁𝗶𝗼𝗻: What’s your go-to bean scope strategy in your services? Have you ever tracked down a production memory leak caused by incorrect scope? #Java #SpringBoot #Microservices #MemoryLeak #BeanScope #SoftwareEngineering #BackendDevelopment #TechTips #Programming
To view or add a comment, sign in
-
Day 10 of the Java Developer Challenge was dedicated to building the first RESTful API Endpoint for reading data. With a solid foundation in the three-tier architecture and MVC pattern, the focus shifted to practical application. By creating a simple GET mapping to retrieve data, a significant milestone was achieved in the transition from theoretical Spring concepts to real-world development. Key Concepts Applied: - **@RestController**: Utilized to define a class that manages HTTP requests and directly returns data (commonly in JSON or XML format) without involving a view name. - **@RequestMapping / @GetMapping**: Specified the URI path and designated the method to handle HTTP GET requests for resource retrieval. - **API Design**: Ensured adherence to REST principles by emphasizing the resource (e.g., /api/users) and selecting the appropriate HTTP verb. - **Separation of Concerns**: Maintained a clear distinction in responsibilities by having the Controller solely manage request handling, delegating business logic (data fetching) to the Service Layer, and returning the output. This practical implementation signifies the crucial transition from theory to application, marking a pivotal moment in the Java Developer Challenge journey! 🚀 #JavaDeveloper #21DayChallenge #Day10 #RESTAPI #SpringBoot #GetMapping #Controller #BackendDevelopment
To view or add a comment, sign in
-
Here is simple open source code that finds context of a java class with a configurable depth. Depth = 1 means the source code of given class C. Depth = 2 means the source code of all classes that C is using. Depth = 3 means the source code of all classes used by depth 2 etc. For generating unit test depth = 1 or 2 seems the best. Bigger context can make gen ai lose focus for this use case but you may need it for a different one. If you build agents in java that work with code this maybe useful. #contextengineering #genai #agents #codegeneration #opensource https://lnkd.in/dShHMEmp
To view or add a comment, sign in
-
Spring Singleton Scope, Synchronization & Thread Safety While reading “Spring Getting Started” and came across something that made me pause a bit the idea of Singleton Beans and how easily they can cause thread-safety issues if you’re not careful. The main idea about Singleton Beans They’re shared. There’s only one instance of a singleton bean in the whole application context and multiple components (and threads) can use it at the same time. Sounds great, right? Efficient, clean... Until two threads start modifying the same instance. That’s when you get a nice little race condition Why synchronization isn’t really the fix You could make your bean synchronized to avoid conflicts but that’s not what singleton beans are made for. Synchronization will protect you, but at a heavy performance cost. Singletons are supposed to be stateless and immutable, not shared mutable objects fighting over state. The better approach: Immutability + Constructor Injection Instead of trying to control concurrency, design around it. 1- Make your beans immutable, no internal state that changes. 2- Use constructor injection so dependencies are final and set once. This simple pattern makes your components thread-safe by design, no synchronization needed. But what if I really need a mutable bean? In those cases, you’ve got a few options: 1- Synchronize access - Simple and safe - Slower, threads block each other 2- Use thread-safe structures - Better performance - Still mutable, so use carefully 3- Change the bean scope Use prototype or request scope if each thread/request needs its own instance - No shared state - More memory usage 4- Externalize the mutable state Keep your singleton stateless and move the data to: - A database - A cache (Redis, etc.) - A state manager Summary - Singleton beans are shared → design them immutable. - Mutable shared state → race conditions. - Constructor injection promotes immutability. - Synchronization = possible, but not ideal. At the end, if you’re working with singleton beans, start with immutability. If mutability is really needed, handle it with proper design or concurrency. #SpringBoot #SpringFramework #SingletonPattern #ThreadSafety #Immutability #CleanCode #Java #BackendDevelopment
To view or add a comment, sign in
-
-
⚡️Java Stream error — but not really an error 😅 While testing Stream operations, I ran into this: "java.lang.IllegalStateException: stream has already been operated upon or closed" At first glance, it looks like a bug — but it’s actually a smart design decision by Java 💡 When you call a terminal operation (like forEach, collect, or count), the Stream is consumed and automatically closed. You can’t reuse it again — and that’s a good thing! ✅ 💡 Why? It prevents data hopping — no one else can reuse the same stream instance. It keeps your data flow pure, isolated, and thread-safe. It ensures any underlying resources (files, DB connections, sockets) are properly released. In short — it’s not an exception to fear; it’s Java protecting your data pipeline from chaos 🔒 Think of a stream like a 🚆 — once it leaves the station (terminal operation), it’s gone. You can always create a new stream for a fresh trip. 😉 #Java #Streams #CleanCode #SoftwareEngineering #ProgrammingInsights #JavaDeveloper
To view or add a comment, sign in
-
-
🚀 Understanding DTOs in Java – Clean, Secure, and Efficient Data Transfer When building robust applications with Spring Boot, one concept that truly improves structure and security is the DTO (Data Transfer Object). A DTO is a simple object used to transfer data between layers — usually between the Controller, Service, and Client (API) — without exposing your Entity directly. 👉 Why use DTOs? ✅ Prevents exposing internal database models ✅ Reduces payload size in API responses ✅ Allows data validation and transformation ✅ Makes your code cleaner and more maintainable 💡 Example: // Entity public class UserEntity { private Long id; private String name; private String password; // should never be sent in response private String email; } // DTO public class UserDto { private String name; private String email; } Then, you map between them using a mapper (manually or tools like ModelMapper or MapStruct): UserDto dto = modelMapper.map(userEntity, UserDto.class); In my recent Spring Boot projects, I use DTOs across every module — from user registration and authentication to bank transactions and payroll management. It not only keeps the architecture layered but also ensures security, scalability, and cleaner APIs. 💬 Do you use DTOs in your backend applications? Or still rely on entities directly? #Java #SpringBoot #DTO #BackendDevelopment #CleanArchitecture #SoftwareEngineering #JavaDeveloper #RESTAPI
To view or add a comment, sign in
-
⚙️ Architecture in Practice — Post #29 Virtual Threads and Structured Concurrency: Two Weeks In Production When Java 21 launched, I was excited. When we actually deployed virtual threads into production, I got cautious. Two weeks later — I’m convinced this is the most meaningful concurrency shift since Java 8 introduced Streams. The Setup We run a mix of latency-sensitive APIs and heavy data pipelines. Classic setup: a pool of 200 threads, async patches, and a dozen hidden choke points. Every small spike meant juggling between blocked I/O and retry storms. We swapped in structured concurrency + virtual threads for one critical path. Not theory — actual deployment. Before → After Metric Before (Thread Pools) After (Virtual Threads) Thread Count 180–220 active threads ~20 carrier threads Avg. Latency (P95) 290 ms 180 ms Memory Footprint +18% during spikes Stable (GC pressure) Error Traceability Nested Futures, Structured task tree, scattered logs. clean cancellation Structured concurrency gave us predictable task lifetimes, and virtual threads finally unlocked simplicity without performance guilt. What I’ve Learned You don’t need to rewrite everything — start small. Use virtual threads for concurrency, not parallelism. Keep your observability tooling updated — thread naming changes everything. Most bugs weren’t in code; they were in how we managed execution context. Modern Java isn’t just catching up — it’s calming down. It’s giving engineers clarity without ceremony. 💬 Are you trying virtual threads in production yet? What’s surprised you the most? #Java21 #VirtualThreads #StructuredConcurrency #PerformanceEngineering #PrincipalEngineer #ArchitectureInPractice
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