@Transactional注解事务不生效问题

Spring 事务配置

 <!-- 事务配置 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="shardingDataSource" />
    </bean>
    
    
    <tx:annotation-driven transaction-manager="transactionManager" />
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="add*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
            <tx:method name="find*" propagation="SUPPORTS"/>
            <tx:method name="*" propagation="SUPPORTS"/>
        </tx:attributes>
    </tx:advice>
    <aop:aspectj-autoproxy />
    <aop:config>
        <aop:pointcut expression="execution(* com.sharding.demo.serviceImpl.*.*(..))" id="mypoint"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="mypoint"/>
    </aop:config>

以上配置,但是在执行时,发现事务不生效,在碰到异常后,发现order表数据没有回滚。

@Override
	@Transactional
	public Long executeOrder(String t) throws BuyStockException{
		Long returnOrderItemId = 0L;
		DefaultKeyGenerator key = new DefaultKeyGenerator();
		int userId = 47;
		Number orderIdKey = key.generateKey();
		Long orderId = orderIdKey.longValue();
		//	Long orderId = Long.parseLong("123");
		logger.info("分布式主键orderId:" + orderId);
		Order order = new Order();
		order.setUserId(userId);
		order.setStatus("1");
		order.setOrderId(orderId);
		Long returnOrderId = orderRepository.insert(order);
		logger.info("插入成功后的returnOrderId:" + returnOrderId);
		
		// 异常
		int i = 1/0; 
		
		
		OrderItem item = new OrderItem();
		item.setOrderId(orderId);
		item.setUserId(userId);
		item.setStatus("1");
		returnOrderItemId = orderItemRepository.insert(item);
		
		return returnOrderItemId; 
		
	}

原因:在配置注解扫描时,将Service层也扫描到了,只要将配置修改为只负责扫描controller层,不要扫描需要配置事物回滚的Service层就可以了。

 <!--注解扫描-->
    <context:component-scan base-package="com.sharding.demo.controller"/>

你可能感兴趣的:(@Transactional注解事务不生效问题)