Search code examples
springtransactionsspring-transactions

Spring disable transactions for a single class method


In my Spring application, I have a class annotated with org.springframework.transaction.annotation.Transactional annotation.

Is it possible to discard transactions for a specific single method of this class without removing @Transactional from class level declarations? If so, please show an example


Solution

  • According to Transactional documentation:

    public @interface Transactional
    
    Describes a transaction attribute on an individual method or on a class.
    

    So additionally to the class-level annotation just define the correct attribute at your method to disable the default transaction handling.

    example:

    @Transactional(propagation=Propagation.NEVER)
    public long notInTransaction(AnythingData anythingData) throws Exception {
       //JDBC code...
    }
    

    Will throw an exception if this method is called inside an active transaction. Whereas Propagation.NOT_SUPPORTED will "suspend" the current transaction and make sure that the method is called non transactional.