Spring Transaction Not Rollback

I have something like this:

@Service
@Transactional
public class ServiceA {

    @Autowired
    SomeDAO1 dao1; 

    @Autowired
    ServiceB serviceB;

    public void methodServiceA() {

        serviceB.someMethodThatRunsInsertIntoDB(); 
        dao1.anotherMethodThatRunsInsertIntoDB(); 

    }

}

@Service
@Transactional
public class ServiceB {

     @Autowired
     Dao2 dao2;

     public void someMethodThatRunsInsertIntoDB() {
          dao2.insertXXX();
     }

}

My problem: if it serviceB.someMethodThatRunsInsertIntoDB()succeeds, but dao1.anotherMethodThatRunsInsertIntoDB()throws an exception, the changes made serviceBare not rolled back. I need to undo these changes if an exception occurs in dao1.anotherMethodThatRunsInsertIntoDB(). How can i do this?

// EDITED

Transaction Configuration in spring -servlet.xml

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
    <property name="jpaDialect">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
    </property>
</bean>

Is this relevant if one dao uses EntityManager and the other dao uses JdbcTemplate to interact with the database?

// UPDATE - EntityManager configuration

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
            <property name="showSql" value="true" />
            <property name="generateDdl" value="true" />
        </bean>
    </property>

+4
source share
4 answers

rollbackFor . , spring . : Spring :

+2

, dao1.anotherMethodThatRunsInsertIntoDB() ( ServiceA).

ServiceB.

@Service
@Transactional(propagation = Propagation.REQUIRED)
public class ServiceB {

: Spring , , bean . , . , , (2- ) , (1- ) .

: , , , . , , . , ( ); ​​ . Spring , EJB CMT. Spring, .


. , , (, RuntimeException). , , , .

@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = YourCheckedException.class))
public class ServiceA {

: , AOP. , Spring beans -, . , -, . , Spring config.

<tx:annotation-driven transaction-manager="transactionManager" />
+1

<tx:annotation-driven/> spring, , .

+1

- @Transactional , .

-, javax.transaction.Transactional org.springframework.transaction.annotation.Transactional, Spring .

You also need to enable transaction management before use @Transactionalusing Spring Boot, we can just do this by tagging the Application class @EnableTransactionManagement.

However, you can do this using the XML ( <tx:annotation-driven />) configuration if you want. Read more at http://docs.spring.io/spring-data/jpa/docs/1.11.0.M1/reference/html/#transactions

0
source

Source: https://habr.com/ru/post/1658422/


All Articles