Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

How does @Transactional work in Spring Boot? स्प्रिंग बूट में @Transactional कैसे काम करता है?

Answer

@Transactional demarcates a method or class as running inside a database transaction. Spring wraps the annotated method in a proxy that begins a transaction before the method runs and commits it after, or rolls it back if a RuntimeException (unchecked exception) is thrown.

Checked exceptions do not trigger a rollback by default unless explicitly configured with rollbackFor. Because it relies on a dynamic proxy, @Transactional has no effect on self-invoked calls within the same class (calling another @Transactional method via this), since the call bypasses the proxy entirely.

@Service
public class OrderService {
    @Transactional(rollbackFor = Exception.class)
    public void placeOrder(Order order) {
        orderRepository.save(order);
        inventoryService.reduceStock(order);
    }
}

@Transactional किसी मेथड या क्लास को डेटाबेस ट्रांज़ैक्शन के अंदर चलने के रूप में चिह्नित करता है। स्प्रिंग एनोटेट मेथड को एक प्रॉक्सी में लपेटता है जो मेथड चलने से पहले ट्रांज़ैक्शन शुरू करता है और बाद में कमिट करता है, या यदि RuntimeException फेंका जाए तो रोलबैक कर देता है।

चेक्ड एक्सेप्शन डिफ़ॉल्ट रूप से रोलबैक ट्रिगर नहीं करते जब तक rollbackFor से स्पष्ट रूप से कॉन्फिगर न किया जाए। डायनामिक प्रॉक्सी पर निर्भर होने के कारण, @Transactional उसी क्लास के अंदर सेल्फ-इनवोक्ड कॉल्स पर कोई प्रभाव नहीं डालता।

@Service
public class OrderService {
    @Transactional(rollbackFor = Exception.class)
    public void placeOrder(Order order) {
        orderRepository.save(order);
        inventoryService.reduceStock(order);
    }
}

Was this answer clear?